Python - Efficient Way To Create 20 Variables?
I need to create 20 variables in Python. That variables are all needed, they should initially be empty strings and the empty strings will later be replaced with other strings. I ca
Solution 1:
Where is my mistake?
There are possibly three mistakes. The first is that 'variable_' + 'a'
obviously isn't equal to 'variable_1'
. The second is the quoting in the argument to exec
. Do
forx in list:
exec("variable_%s = ''" % x)
to get variable_a
etc.
The third mistake is that you're not using a list
or dict
for this. Just do
variable = dict((x, '') for x in list)
then get the contents of "variable" a
with variable['a']
. Don't fight the language. Use it.
Solution 2:
I have the same question as others (of not using a list or hash), but if you need , you can try this:
for i in xrange(1,20):
locals()['variable_%s' %i] = ''
Im assuming you would just need this in the local scope. Refer to the manual for more information on locals
Solution 3:
never used it, but something like this may work:
liste = ['a', 'b']
for item in liste:
locals()[item] = ''
Post a Comment for "Python - Efficient Way To Create 20 Variables?"