Generating Variable Names On Fly In Python
Is there a way I can generate variable names in python in a loop and assign values to them? For example, if I have prices = [5, 12, 45] I want price1 = 5 price2 = 12 price3 = 45
Solution 1:
If you really want to create them on the fly you can assign to the dict that is returned by either globals()
or locals()
depending on what namespace you want to create them in:
globals()['somevar'] = 'someval'print somevar # prints 'someval'
But I wouldn't recommend doing that. In general, avoid global variables. Using locals()
often just obscures what you are really doing. Instead, create your own dict and assign to it.
mydict = {}
mydict['somevar'] = 'someval'print mydict['somevar']
Learn the python zen; run this and grok it well:
>>> importthis
Solution 2:
Though I don't see much point, here it is:
for i in xrange(0, len(prices)):
exec("price%d = %s" % (i + 1, repr(prices[i])));
Solution 3:
On an object, you can achieve this with setattr
>>>classA(object): pass>>>a=A()>>>setattr(a, "hello1", 5)>>>a.hello1
5
Solution 4:
I got your problem , and here is my answer:
prices = [5, 12, 45]
list=['1','2','3']
for i inrange(1,3):
vars()["prices"+list[0]]=prices[0]
print ("prices[i]=" +prices[i])
so while printing:
price1 = 5price2 = 12price3 = 45
Solution 5:
Another example, which is really a variation of another answer, in that it uses a dictionary too:
>>>vr={} ...for num inrange(1,4): ... vr[str(num)] = 5 + num...>>>print vr["3"]
8
>>>
Post a Comment for "Generating Variable Names On Fly In Python"