Python - 创建 20 个变量的有效方法?

发布于 2024-11-23 18:23:22 字数 413 浏览 1 评论 0原文

我需要在 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技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

冰魂雪魄 2024-11-30 18:23:22

我的错误在哪里?

可能存在三个错误。首先是 'variable_' + 'a' 显然不等于 'variable_1'。第二个是 exec 参数中的引用。获取

for x in list:
    exec("variable_%s = ''" % x)

variable_a 等。

第三个错误是您没有为此使用 listdict 。只需

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

使用 variable['a'] 获取“变量”a 的内容即可。不要对抗语言。使用它。

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.

恋竹姑娘 2024-11-30 18:23:22

我和其他人有同样的问题(不使用列表或哈希),但如果您需要,您可以尝试这个:

for i in xrange(1,20):
    locals()['variable_%s' %i] = ''

我假设您只需要在本地范围内使用它。有关 locals 的更多信息,请参阅手册

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

任谁 2024-11-30 18:23:22

从未使用过它,但类似这样的东西可能会起作用:

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

never used it, but something like this may work:

liste = ['a', 'b']
for item in liste:
    locals()[item] = ''
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文