tags:

views:

93

answers:

4

Hello,

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:

  1. A combination (tuple) of array names is created.
  2. The combination (tuple) is passed to a function as an argument.
  3. The function concatenates related arrays and processes the result.

Hopefully this question is not too cryptic. Thanks for responses in advance :-)

+2  A: 

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.

David M.
Yes, list comprehensions with locals() do the job! Thank you :-)
+2  A: 

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))
Constantin
+1  A: 

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])
rod
I prefer to avoid `eval` as it can bring more problems than benefits.
If it's safe to use locals, it's safe to use eval. (Neither should be used if the namespace and inputs are not controlled.) It doesn't pay to be irrationally eval-phobic. Here, however, using locals is probably easier to read, since its meaning is more specific.
David M.
+2  A: 

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]
unutbu