为什么list.remove仅删除第二个项目? [英] Why is list.remove only removing every second item?

查看:59
本文介绍了为什么list.remove仅删除第二个项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Python 2.7.2 IDLE解释器中:

In my Python 2.7.2 IDLE interpreter:

>>> mylist = [1, 2, 3, 4, 5]
>>> for item in mylist:
        mylist.remove(item)

>>> mylist
[2, 4]

为什么?

推荐答案

这是因为当您遍历列表时,

It's because when you iterate over a list, python keeps track of the index in the list. Consider the following code instead:

for i in range(len(mylist)):
    if i >= len(mylist):
       break
    item = mylist[i]
    mylist.remove(item)

如果我们跟踪此内容(这实际上是python在您的代码中所做的事情),那么我们会看到,当我们删除列表中的一个项目时,右边的数字向左移动一个位置以填补当出现以下情况时的空白我们删除了该项目.正确的项目现在位于索引i处,因此它实际上不会在迭代中被看到,因为接下来发生的事情是,对于for循环的下一次迭代,我们将i递增.

If we track this (which is essentially what python is doing in your code), then we see that when we remove an item in the list, the number to the right shifts one position to the left to fill the void left when we removed the item. The right item is now at index i and so it will never actually get seen in the iteration because the next thing that happens is we increment i for the next iteration of the for loop.

现在需要一些聪明的东西.相反,如果我们向后遍历该列表,则将清除该列表:

Now for something a little clever. If instead we iterate over the list backward, we'll clear out the list:

for item in reversed(mylist):
    mylist.remove(item)

这里的原因是,在for循环的每次迭代中,我们都从列表末尾删除了一个项目.由于我们总是从头开始删除项目,因此无需进行任何更改(假设列表中的唯一性-如果列表不是唯一的,则结果是相同的,但参数会变得更加复杂).

The reason here is that we're taking an item off the end of the list at each iteration of the for loop. Since we're always taking items off the end, nothing needs to shift (assuming uniqueness in the list -- If the list isn't unique, the result is the same, but the argument gets a bit more complicated).

当然,如果您希望从列表中删除所有项目,则可以非常轻松地做到这一点:

Of course, If you're looking to remove all the items from a list, you can do that really easily:

del mylist[:]

甚至是切片分配:

mylist[:] = []

(我之所以提到后者,是因为用其他甚至不需要相同长度的项替换列表的段会很有用.)

(I mention the latter because it can be useful to replace segments of a list with other items which don't even need to be the same length).

这篇关于为什么list.remove仅删除第二个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆