0

I have a big number of variables that have an increasing number in their name:

var0 = 2
var1 = 6
...
var999 = 19

Is there an easy way (maybe with a loop) to create a numpy array that contains the values of the variables as elements?

list[0] = 2
list[1] = 6
...
list[999] = 19
Ethunxxx
  • 1,229
  • 4
  • 16
  • 34
  • 1
    Why do you have all these variables in the first place ? – JulienD Jun 22 '16 at 13:57
  • Just to check if it's an x-y problem: Where do these variables come from? – Dschoni Jun 22 '16 at 13:58
  • I got a file containing these variable definitions. Of course, I know it's not a clever way to store them like that :-). What do you mean by x-y-problem? – Ethunxxx Jun 22 '16 at 14:01
  • 1
    Can you show the file, or at least the structure of the file? PArsing from a file would be a lot easier. – Dschoni Jun 22 '16 at 14:01
  • If you have acces to the code that produces the variables in the first place, it would also be a good idea, to save them in an easier format (e.g. pickle a dictionary) – Dschoni Jun 22 '16 at 14:11
  • How are you loading or importing this file? Don't use `from ... import *`. – hpaulj Jun 22 '16 at 16:12

6 Answers6

1

If you have a file, say test.txt that looks like that:

var0 = 1
var1 = 2
var3 = 15

you can do:

t = open('test.txt',r)
data = t.readlines()
t.close()
for line in data:
    name,value = line.split('=')
    name.strip()
    value = int(value.strip())

and then do whatever you want with those pairs. Put them in a list, process further etc...

Dschoni
  • 3,714
  • 6
  • 45
  • 80
0

This should work, using vars() and assuming that no other variable name in the environment starts with "var":

{int(x[0][3:]) : x[1] for x in vars().items() if x[0].startswith('var')}

Example:

>>> var1 = 8
>>> var2 = 98
>>> {int(x[0][3:]) : x[1] for x in vars().items() if x[0].startswith('var')}
{1: 8, 2: 98}

You can also use locals(): What's the difference between globals(), locals(), and vars()?

Community
  • 1
  • 1
JulienD
  • 7,102
  • 9
  • 50
  • 84
0

you can use the globals or locals function like below:

a1 = 5 a2 = 6 alist = [] for i in range(1,3,1): alist.append(globals()['a'+str(i)])

Akarsh
  • 389
  • 5
  • 15
0

Variables in Python are always available through your locals (or globals, if in a narrower scope than their definition) dictionary:

>>> x = 2
>>> y = 'Hello !'
>>> 'x' in locals()
True
>>> locals()['x']
2
>>> locals()['y']
'Hello !'

Using this, it would be simple to iterate through your variables:

i = 0
values = []
while 'var{}'.format(i) in locals():
    values.append(locals()['var{}'.format(i)])
    i += 1
arr = np.array(values)

(There might be much more elegant ways of doing that, but you get the idea)

As mentionned in comments though, this is a very brittle way of going about it: I mentionned locals vs globals, but know that getting your hands dirty with 'internals' dictionaries is very messy and unreliable. Never use that in production ! If you have a file of variables in the format varXXX = YYYY, you can easily parse that:

values = []
with open('./myfile.xyz', 'r') as f:
    for line in f:
        values.append(float(line.split('=')[1].strip()))

If the format is more complex (maybe containing other things, or potentially invalid data), you still have a lot of parsing options: the csv module might be a good way to start.

val
  • 8,459
  • 30
  • 34
0

Is it a python file (.py)? You can try this workaround:

Add the following lines to the end of where you have the variables:

from operator import itemgetter # this should go up

d = {k[3:]:v for k, v in locals().items() if k.startswith('var')}
sorted_d = sorted(d.items(), key=itemgetter(0))
lst = [i[1] for i in sorted_d]
# [2, 6, ..., 19]

Provided no other variables start with var

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
0

If the variables are in a file in valid Python syntax, they can be imported and parsed from there.

from file.py import *

puts them into the local name space. But if we don't use * we can isolate them

In [1313]: import stack3797 as varN

In [1314]: values = {i:v for i,v in  vars(varN).items() if i.startswith('var')}

In [1315]: values
Out[1315]: 
{'var8': 19,
 'var2': 7,
 'var7': 17,
 'var0': 3,
 'var6': 15,
 'var3': 9,
 'var9': 21,
 'var1': 5,
 'var5': 13,
 'var4': 11}

Then any other the other answers that work from locals() can be used to convert this dictionary to an array.

If the varN labeling is consecutive, we can figure out the size of the resulting array from the size of this dictionary. Otherwise we might have to find the maximum value first.

or we can make a list of lists right away:

values = [[int(i[3:]),v] for i,v in  vars(varN).items() if i.startswith('var')]

and turn it into a array with

In [1328]: np.array(values).T
Out[1328]: 
array([[ 8,  6,  0,  1,  3,  5,  2,  7,  9,  4],
       [19, 15,  3,  5,  9, 13,  7, 17, 21, 11]])

That still needs a x[i] = value mapping.

hpaulj
  • 221,503
  • 14
  • 230
  • 353