[英]Question about python3 list deletion。Why can't I delete an even number with an odd number?
I entered a line of code 我输入了一行代码
li = [1,2,3,4,5,6,7]
for i in li :
if i%2 == 0:
li.remove(i)
print(li)
[1, 3, 5, 7]
it's ok 没关系
two 二
li = [2,4,5,6,7]
for i in li :
if i%2 == 0:
li.remove(i)
print(li)
[4, 5, 7]
it's ok ,But I don't know why 没关系,但是我不知道为什么
three 三
li = [2,6,4,5,4,7]
for i in li :
if i%2 == 0:
li.remove(i)
print(li)
[6, 5, 7]
it's ok ,Same as the second one, but I do not know why 可以,与第二个相同,但是我不知道为什么
four 四
li = [2,6,4,5,6,7]
for i in li :
if i%2 == 0:
li.remove(i)
print(li)
[5, 6, 7]
I broke down 我坏了
five 五
li = [2,6,5,6,6,7]
for i in li :
if i%2 == 0:
li.remove(i)
print(li)[5, 6, 6, 7]
😭😭😭 😭😭😭
Sorry, I don't know English very much, with the help of Google Translate 抱歉,在Google翻译的帮助下,我不太懂英语
Any help would be appreciated. 任何帮助,将不胜感激。
As @Lennart Regebro mentioned in his answer , since your modifying the list each time you 're iterating over it, it's safer to get a copy of that list and iterate over that copy, because you will get unexpected results otherwise: 正如@Lennart Regebro在他的回答中提到的那样,由于您每次在列表上进行迭代时都要修改列表,因此获取该列表的副本并对该副本进行迭代是更安全的,因为否则您将得到意外的结果:
li = [2,6,5,6,6,7]
for i in li[:]: #Notice the [:] notation, it is used to create a copy of a list.
if i%2 == 0:
li.remove(i)
print(li)
Result: 结果:
[5, 7]
You are modifying the list while looping over it which means after every number you remove the loop will avoid the first value after the removed value and take the second next value till the loop end. 您在遍历列表时修改列表,这意味着在删除每个数字之后,循环将避免删除值之后的第一个值,并取第二个下一个值,直到循环结束。
You can make a copy of the list to iterate over and remove from the original one as follows: 您可以复制列表以进行迭代,并从原始列表中删除,如下所示:
li = [2,6,5,6,6,7]
li_copy = li.copy()
for i in li_copy :
if i%2 == 1:
li.remove(i)
print(li)
Ahmed Hawary has pointed out your mistake. 艾哈迈德·哈瓦里(Ahmed Hawary)指出了您的错误。 You can also try this, list comprehension makes it very easy to modify existing list based on any condition. 您也可以尝试使用此方法,列表理解功能使您可以轻松地基于任何条件修改现有列表。
[i for i in li if i%2!=0] [如果i%2!= 0,则表示我在li中为i]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.