我想切换列表的第二个元素:
s = [False] * 5
for item in s[::2]:
item = not item
print(s)
但这是行不通的。
[False, False, False, False, False]
但是,这可以按预期工作:
for i in range(0, len(s), 2):
s[i] = not s[i]
print(s)
[True, False, True, False, True]
为什么会这样呢?
python大神给出的解决方案
因为当你做
item = not item
您实际上正在做的是将对数组中对象的引用更改为对数组外对象的另一个引用。 item
只是对数组内部对象的引用的副本。
第二个代码按预期工作,因为它更改了数组本身而不是引用副本中的引用。