[英]For loop resulting in wrong output
The code snippet below results in [5,7,18,23,50], why 5 is not getting removed from the resultant list?下面的代码片段导致 [5,7,18,23,50],为什么 5 没有从结果列表中删除?
list1 = [11, 5, 17, 18, 23, 50]
not_needed = {11, 5}
for e in list1:
if e in not_needed:
list1.remove(e)
else:
pass
print(list1)
Because you are modifying the list as it is being iterated over.因为您正在修改列表,因为它正在迭代。
When you read the first item, it is 11
so it gets removed.当您阅读第一项时,它是
11
因此它被删除。
When you read the second item, it is 17
, because the first item was removed.当您阅读第二项时,它是
17
,因为第一项已被删除。 The item 5
is now the new first item and you never get to check it.项目
5
现在是新的第一个项目,您永远无法检查它。
Because once the 11 is removed, the 5 gets skipped during iteration.因为一旦删除了 11,在迭代过程中就会跳过 5。 This is why you never iterate over a list and remove from it at the same time.
这就是为什么您永远不会迭代列表并同时从列表中删除的原因。
list1 = [11, 5, 17, 18, 23, 50]
not_needed = {11, 5}
for e in not_needed:
list1.remove(e)
print(list1)
Gives:给出:
[17, 18, 23, 50]
This is because after first iteration item 11 is deleted and it goes for second index which becomes 17 in list [5,17,18,23,50] The best way to rectify this is to take result list so that you dont have to mutate "list1"这是因为在第一次迭代后,第 11 项被删除,第二个索引变成了列表 [5,17,18,23,50] 中的 17 纠正这个问题的最好方法是获取结果列表,这样你就不必变异“列表1”
list1 = [11, 5, 17, 18, 23, 50]
not_needed = {11, 5}
result = []
for e in list1:
if e in not_needed:
pass
else:
result.append(e)
print(result)
Use list comprehension when looping over a list and modifying it at the same time.在循环列表并同时修改它时使用列表理解。
list1 = [x for x in list1 if not x in not_needed]
list1
[17, 18, 23, 50]
Further details on this here: https://www.analyticsvidhya.com/blog/2016/01/python-tutorial-list-comprehension-examples/此处的更多详细信息: https : //www.analyticsvidhya.com/blog/2016/01/python-tutorial-list-comprehension-examples/
for loop in python runs on the indexes not on each element . python 中的 for 循环在索引上运行,而不是在每个元素上运行。
When it finds 11 and removes it from list1, list1 becomes [5, 17, 18, 23, 50] but the loop is now on second element.当它找到 11 并将其从 list1 中删除时,list1 变为 [5, 17, 18, 23, 50] 但循环现在位于第二个元素上。 So it misses 5 in the list.
所以它错过了列表中的 5。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.