我需要以下列方式访问给定名称的变量:
a = numpy.array([1,2,3])
b = numpy.array([4,5,6])
names = ('a', 'b')
然后,我将变量names
传递给函数,比如numpy.hstack(),以获得与numpy.hstack((a,b))
相同的结果。
最好的pythonic方式是什么?
目的是什么?我有一个函数,它接受numpy数组的名称并将相关数组(在函数中定义)堆叠在一起来处理它们。我需要创建这些数组的所有可能组合,因此:
希望这个问题不是太神秘。感谢您提前回复: - )
答案 0 :(得分:2)
您可以使用内置函数locals
,它返回表示本地名称空间的字典:
>>> a = 1
>>> locals()['a']
1
>>> a = 1; b = 2; c = 3
>>> [locals()[x] for x in ('a','b','c')]
[1, 2, 3]
您也可以将数组存储在自己的字典或模块中。
答案 1 :(得分:2)
如果我理解你的问题,你必须使用locals()
这样:
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))
答案 2 :(得分:2)
由于您正在使用numpy,并希望按名称引用数组,因此您似乎应该使用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)
定义重新排列arr
后,您可以按名称访问各个列:
In [57]: arr['a']
Out[57]: array([1, 2, 3])
In [58]: arr['c']
Out[58]: array([7, 8, 9])
因此,要生成名称组合,并将列与np.hstack组合,您可以这样做:
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]
答案 3 :(得分:1)
也许我误解了,但我会使用内置函数eval
并执行以下操作。我不知道它是否特别是pythonic,请注意。
numpy.concatenate([eval(n) for n in names])