Python-创建20个变量的有效方法吗? [英] Python - efficient way to create 20 variables?

查看:102
本文介绍了Python-创建20个变量的有效方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Python中创建20个变量.这些变量都是必需的,它们最初应为空字符串,然后将空字符串替换为其他字符串.我无法在需要时根据需要创建变量,因为我还有一些if/else语句,需要检查变量是否仍然为空或是否已经等于其他字符串.

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.

代替写作

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

我想过类似的事情

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

此代码不会导致错误,但仍然不能满足我的期望-变量不是使用名称"variable_1"创建的,依此类推.

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?

可能有三个错误.首先是'variable_' + 'a'显然不等于'variable_1'.第二个是exec参数中的引号.做

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)

获取variable_a

第三个错误是您没有为此使用listdict.做吧

The third mistake is that you're not using a list or dict for this. Just do

variable = dict((x, '') for x in list)

然后使用variable['a']获取变量" a的内容.不要和语言打架.使用它.

then get the contents of "variable" a with variable['a']. Don't fight the language. Use it.

这篇关于Python-创建20个变量的有效方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆