如何在 Python 中的循环中重命名变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16057689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to rename variables in a loop in Python
提问by apkdsmith
I want to run a program in Python which loops several times, creating a NEW array each time - i.e. no data is overwritten - with the array named with a reference to the loop number, so that I can call it in subsequent loops. For instance, I might want to create arrays x0, x1, x2, ..., xi in a loop running from 0 to i, and then call each of these in another loop running over the same variables. (Essentially the equivalent of being able to put a variable into a string as 'string %d %(x)').
我想在 Python 中运行一个程序,该程序循环多次,每次创建一个新数组 - 即没有数据被覆盖 - 使用对循环编号的引用命名的数组,以便我可以在后续循环中调用它。例如,我可能想在从 0 到 i 的循环中创建数组 x0、x1、x2、...、xi,然后在运行相同变量的另一个循环中调用这些数组中的每一个。(本质上相当于能够将变量放入字符串中'string %d %(x)')。
采纳答案by StarlitGhost
Using a dict:
使用字典:
arraysDict = {}
for i in range(0,3):
arraysDict['x{0}'.format(i)] = [1,2,3]
print arraysDict
# {'x2': [1, 2, 3], 'x0': [1, 2, 3], 'x1': [1, 2, 3]}
print arraysDict['x1']
# [1,2,3]
Using a list:
使用列表:
arraysList = []
for i in range(0,3):
arraysList.append([1,2,3])
print arraysList
# [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
print arraysList[1]
# [1, 2, 3]
回答by Paco
回答by MartinStettner
You can access the globals()dictionary to introduce new variables. Like:
您可以访问globals()字典以引入新变量。喜欢:
for i in range(0,5):
globals()['x'+str(i)] = i
After this loop you get
在这个循环之后你得到
>>> x0, x1, x2, x3, x4
(0, 1, 2, 3, 4)
Note, that according to the documentation, you should not use the locals()dictionary, as changes to this one may not affect the values used by the interpreter.
请注意,根据文档,您不应使用locals()字典,因为对此字典的更改可能不会影响解释器使用的值。
回答by glglgl
Relying on variables's names and changing them is not the best way to go.
依赖变量的名称并更改它们并不是最好的方法。
As people already pointed out in comments, it would be better to use a dict or a list instead.
正如人们在评论中已经指出的那样,最好使用 dict 或列表。

