I want to run a program in Python which loops several times, creating a NEW array each time - i.e. no data is overwritten - with the array named with a reference to the loop number, so that I can call it in subsequent loops. For instance, I might want to create arrays x0, x1, x2, ..., xi in a loop running from 0 to i, and then call each of these in another loop running over the same variables. (Essentially the equivalent of being able to put a variable into a string as 'string %d %(x)').
-
15The best way is not to do this... use a list (or dictionary) insteadjamylak– jamylak2013-04-17 10:30:24 +00:00Commented Apr 17, 2013 at 10:30
-
3Your problem is that you are using local variables where you should be using a list or dictionary instead.Martijn Pieters– Martijn Pieters2013-04-17 10:32:35 +00:00Commented Apr 17, 2013 at 10:32
Add a comment
|
4 Answers
You can access the globals() dictionary to introduce new variables. Like:
for i in range(0,5):
globals()['x'+str(i)] = i
After this loop you get
>>> x0, x1, x2, x3, x4
(0, 1, 2, 3, 4)
Note, that according to the documentation, you should not use the locals() dictionary, as changes to this one may not affect the values used by the interpreter.
5 Comments
John La Rooy
Except that it doesn't work for
locals()MartinStettner
Yes, I already changed my answer. Although it seems to work, if you only introduce new variables (and don't change their value afterwards)
bruno desthuilliers
Note to anyone reading this answer : PLEASE DONT DO SUCH A STUPID THING. The correct solution is to use a dict or list.
MartinStettner
I didn't suggest that this is a good way to do anything. But I believe it is a correct answer to a perfectly valid original question. Perhaps you might want to reread the SO section on downvoting ...
MartinStettner
@brunodesthuilliers There are a couple of scenarios where it might make sense to modify the global environment (there might be a reason for the presence of the
globals() dict after all...) Without knowing anything more, you cannot say, if this is the case here.Using a dict:
arraysDict = {}
for i in range(0,3):
arraysDict['x{0}'.format(i)] = [1,2,3]
print arraysDict
# {'x2': [1, 2, 3], 'x0': [1, 2, 3], 'x1': [1, 2, 3]}
print arraysDict['x1']
# [1,2,3]
Using a list:
arraysList = []
for i in range(0,3):
arraysList.append([1,2,3])
print arraysList
# [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
print arraysList[1]
# [1, 2, 3]
Comments
You can create an object for this, and then use the setattr function for this. Basically, it will work like this:
setattr(myobject, 'string', value)
It is the same as doing : myobject.string = value