需要在 Python 中创建帮助变量 [英] need help-variable creation in Python
问题描述
我想将变量创建为 a1
,a2
,a3
...a10
.为此,我使用了 for 循环.随着循环中的变量递增,我需要像上面一样创建一个变量.
I want to create variables as a1
,a2
,a3
...a10
.
For that I used a for loop. As the variable in loop increments I need to create a variable as above.
谁能给我一个想法?
在创建时,我还需要能够为它们赋值.
At the time of creation I also need to be able to assign values to them.
这就是我遇到语法错误的地方.
That's where I'm getting syntax error.
推荐答案
按照 S.Lott 所说的,你也可以使用 dict,如果你真的需要唯一的名称并且项目的顺序并不重要:>
Following what S.Lott said, you can also use a dict, if you really nead unique names and that the order of the items is not important:
data = {}
for i in range(0, 10):
data['a%d' % i] = i
>>>data
{'a1': 1, 'a0': 0, 'a3': 3, 'a2': 2, 'a5': 5, 'a4': 4, 'a7': 7, 'a6': 6, 'a9': 9, 'a8': 8}
我想补充一点,像您想要的那样自动创建变量是非常危险的,因为您可能会覆盖可能已经存在的变量.
I would add that this is very dangerous to automate variable creation like you want to do, as you might overwrite variables that could already exist.
这篇关于需要在 Python 中创建帮助变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!