我正在寻找一种方法让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
答案 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)
仍会导致original
为Python strings are immutable