如何在Python中的循环中重命名变量 [英] How to rename variables in a loop in Python
问题描述
我想在Python中运行一个循环多次的程序,每次创建一个NEW数组-即没有数据被覆盖-命名数组时要引用循环号,这样我就可以在后续循环中调用它.例如,我可能想在从0到i的循环中创建数组x0,x1,x2,...,xi,然后在另一个循环中对相同变量进行调用,以分别调用数组x0,x1,x2,...,xi.(基本上相当于能够将变量作为'string%d%(x)'
放入字符串中).
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)'
).
推荐答案
使用字典:
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]
使用列表:
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]
这篇关于如何在Python中的循环中重命名变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!