8

I have this code:

I restated the problem formulation somewhat. Not sure if etiquette is to post a new question. If so, my bad

import numpy as np
a = np.array([0,0])
b = np.array([1,0])
c = np.array([2,0])

my_array_list = [a,b,c]
for my_array in my_array_list:
    np.save('string_that is representative of my_array',my_array)

where 'string that is representative of my array' equals to 'a', 'b', 'c' or similar.

There is likely a better way to solve this, I can just not come up with one right now.

What is the best way to do this, fast and efficiently?

2
  • 2
    No, because it might have more than one name (e.g., if you do other_name = my_array). Commented Jan 24, 2016 at 20:07
  • 1
    Possible duplicate: stackoverflow.com/questions/18425225/… Commented Jan 24, 2016 at 20:14

3 Answers 3

15

I can suggest you that function:

import numpy as np

def namestr(obj, namespace):
    return [name for name in namespace if namespace[name] is obj]

my_numpy = np.zeros(2)
print(namestr(my_numpy, globals()))

With output:

['my_numpy']
Sign up to request clarification or add additional context in comments.

1 Comment

thanks George, beautiful and simple solution. I actually changed the implementation to: return [name for name in namespace if namespace[name] is obj][0] and that is exactly what I needed
1

Excellent solution by @GeorgePetrov above. Here just expanding it as tutorial:
Given: list of variables of any type e.g. [a,bb,c,d,e]
Output: list of varibles' names in string form e.g. ['a','bb', 'c', 'd', 'e']

import numpy as np

a = np.array([0,0])
bb = np.array([1,0,9,9])
c = ["cvghvgh", "kkk"]
d = 88
e = "bb"

variable_list = [a,bb,c,d,e]
str_var_list=[]

for i in range(len(variable_list)):
    str_var_list.append( [name for name in globals() if globals()[name] is variable_list[i]][0] )

print(str_var_list)

Comments

0

How about you initialize it as a dictionary with key value pairs. this way you reference the key (string) or the value (ndarray)

import numpy as np
a = np.array([0,0])
b = np.array([1,0])
c = np.array([2,0])

my_array_list = {'a':a,'b':b,'c':c}
for key, value in my_array_list.items():
    np.save('{} is representative of {}'.format(key, value)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.