Python - 创建 20 个变量的有效方法?
我需要在 Python 中创建 20 个变量。这些变量都是必需的,它们最初应该是空字符串,空字符串稍后将被其他字符串替换。我无法在需要时根据需要创建变量,因为我还有一些 if/else 语句需要检查变量是否仍然为空或已经等于其他字符串。
我没有写,而是
variable_a = ''
variable_b = ''
....
想到了这样的代码:
list = ['a', 'b']
for item in list:
exec("'variable_'+item+' = '''")
此代码不会导致错误,但仍然没有达到我的预期 - 变量不是用名称“variable_1”创建的,依此类推。
我的错误在哪里?
谢谢,樵夫
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
可能存在三个错误。首先是
'variable_' + 'a'
显然不等于'variable_1'
。第二个是exec
参数中的引用。获取variable_a
等。第三个错误是您没有为此使用
list
或dict
。只需使用
variable['a']
获取“变量”a
的内容即可。不要对抗语言。使用它。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 toexec
. Doto get
variable_a
etc.The third mistake is that you're not using a
list
ordict
for this. Just dothen get the contents of "variable"
a
withvariable['a']
. Don't fight the language. Use it.我和其他人有同样的问题(不使用列表或哈希),但如果您需要,您可以尝试这个:
我假设您只需要在本地范围内使用它。有关 locals 的更多信息,请参阅手册
I have the same question as others (of not using a list or hash), but if you need , you can try this:
Im assuming you would just need this in the local scope. Refer to the manual for more information on locals
从未使用过它,但类似这样的东西可能会起作用:
never used it, but something like this may work: