如何将变量添加到变量中

时间:2015-10-22 05:54:19

标签: python python-3.x

t = 0
prices = x
for t in range(0,5):
    t += 1
    prices@t = y

我希望价格变量根据t进行更改,例如prices1prices2prices3等。

2 个答案:

答案 0 :(得分:3)

你真的不应该自动创建局部变量。最好将类似值的集合保存在某种类型的容器变量中

您可以使用list来实现此目标

prices = []
for t in range(0, 5):
    prices.append(y)

或者如果您想预先分配正确大小的列表:

prices = [0] * 5
for t in range(0, 5):
    prices[t] = y 

或者dict

prices = {}
for t in range(0, 5):
    prices[t] = y

答案 1 :(得分:1)

可能不是问题的最佳解决方案,但您可以使用exec()来完成此操作

y = 10
for t in range(0,5):
    y = y+t
    exec("prices"+ str(t) + "= y")
print(prices0)
print(prices1)
print(prices2)
print(prices3)