Accessing variables by their names in a tuple
I need to access variables given their names, in the following way:
a = numpy.array([1,2,3])
b = numpy.array([4,5,6])
names = ('a', 'b')
Then, I pass the variable names
to a function, say numpy.hstack() to obtain the same result as with numpy.hstack((a,b))
.
What is the best pythonic way to do so?
And what is the purpose? I have a function, that accepts names of numpy arrays and stacks the related arrays (defined in the function) together to process them. I need to create all possible combinations of these arrays, hence:
- A combination (tuple) of array names is created.
- The combination (tuple) is passed to a function as an argument.
- The function concatenates related arrays and processes the result.
Hopefully this question 开发者_JAVA百科is not too cryptic. Thanks for responses in advance :-)
You can use the built-in function locals
, which returns a dictionary representing the local namespace:
>>> a = 1
>>> locals()['a']
1
>>> a = 1; b = 2; c = 3
>>> [locals()[x] for x in ('a','b','c')]
[1, 2, 3]
You could also simply store your arrays in your own dictionary, or in a module.
If i understood your question correctly, you would have to use locals()
like this:
def lookup(dic, names):
return tuple(dic[name] for name in names)
...
a = numpy.array([1,2,3])
b = numpy.array([4,5,6])
names = ('a', 'b')
numpy.hstack(lookup(locals(), names))
Since you are using numpy, and wish to refer to arrays by names, it seems perhaps you should be using a recarray:
import numpy as np
import itertools as it
a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.array([7,8,9])
names=('a','b','c')
arr=np.rec.fromarrays([a,b,c],names=names)
Once you define the recarray arr
, you can access the individual columns by name:
In [57]: arr['a']
Out[57]: array([1, 2, 3])
In [58]: arr['c']
Out[58]: array([7, 8, 9])
So, to generate combinations of names, and combine the columns with np.hstack, you could do this:
for comb in it.combinations(names,2):
print(np.hstack(arr[c] for c in comb))
# [1 2 3 4 5 6]
# [1 2 3 7 8 9]
# [4 5 6 7 8 9]
Maybe I misunderstood, but I would just use the built-in function eval
and do the following. I don't know if it's particularly pythonic, mind you.
numpy.concatenate([eval(n) for n in names])
精彩评论