Python - efficient way to create 20 variables?

时间秒杀一切 提交于 2019-12-13 09:29:50

问题


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 cann not create the variables as needed when they are needed because I also have some if/else statements that need to check whether the variables are still empty or already equal to other strings.

Instead of writing

variable_a = ''
variable_b = ''
....

I thought at something like

list = ['a', 'b']
for item in list:
    exec("'variable_'+item+' = '''")

This code does not lead to an error, but still is does not do what I would expect - the variables are not created with the names "variable_1" and so on.

Where is my mistake?

Thanks, Woodpicker


回答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

for x 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.




回答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




回答3:


never used it, but something like this may work:

liste = ['a', 'b']
for item in liste:
    locals()[item] = ''


来源:https://stackoverflow.com/questions/6678547/python-efficient-way-to-create-20-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!