Python中的Foreach无法按预期工作 [英] Foreach in Python not working as expected
本文介绍了Python中的Foreach无法按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
s = [False] * 5
for s in [[2]:
item = not item
print(s)
但它不起作用。
[False,False,False,False,False]
然而,按预期工作:
0,len(s),2):
s [i] = not s [i]
print(s)
[True,False,True, False,True]
解决方案
因为当你做
item = not item
实际做的是将数组中引用改为另一个引用数组。 item
只是数组内对象引用的副本。
第二个代码按预期工作,它会改变数组本身的引用,而不是引用副本。
I want to toggle every second element of a list:
s = [False] * 5
for item in s[::2]:
item = not item
print(s)
But it doesn't work.
[False, False, False, False, False]
This however, works as expected:
for i in range(0, len(s), 2):
s[i] = not s[i]
print(s)
[True, False, True, False, True]
Why is this happening?
解决方案
Because when you do
item = not item
What you're actually doing is to change the reference to an object in the array with another reference to an object outside the array. item
is just a copy of a reference to an object inside the array.
The second code works as expected because it changes the reference in the array itself, not in a reference copy.
这篇关于Python中的Foreach无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文