用于循环遍历变量列表

时间:2017-04-06 00:22:59

标签: python python-3.x loops python-3.5

我正在寻找一种方法让for循环能够遍历变量列表,并能够将它们用作这样的变量:

>>> a = "original"
>>> b = "original"
>>> c = "original"
>>> d = "original"
>>> for i in [a,b,c,d]:
        i = "change"
>>> print(a,b,c,d)
change change change change

2 个答案:

答案 0 :(得分:1)

您的初始代码不起作用,因为设置" i"的值实际上并没有设置变量" a"," b"等等的值。

a = "original"
b = "original"
c = "original"
d = "original"
list = [a,b,c,d]
for i in range(0,len(list)):
    list[i] = "change"
print(list)

答案 1 :(得分:0)

正如对原始问题的评论所指出的那样,这有点味道,你可能想要考虑一种解决实际问题的不同方法。话虽这么说,你可以在这里完成你想要做的事情:

a = "original"
b = "original"
c = "original"
d = "original"
l = [a, b, c, d]

for idx, val in enumerate(l):
    l[idx] = "change"

print(l)

这导致:

['change', 'change']

请注意,print(a)仍会导致originalPython strings are immutable