在 Python 中遍历列表时删除元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1352885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 22:02:07  来源:igfitidea点击:

Remove elements as you traverse a list in Python

pythonlistloopsiteratorpython-datamodel

提问by user102008

In Java I can do by using an Iteratorand then using the .remove()method of the iterator to remove the last element returned by the iterator, like this:

在 Java 中,我可以使用 anIterator然后使用.remove()迭代器的方法删除迭代器返回的最后一个元素,如下所示:

import java.util.*;

public class ConcurrentMod {
    public static void main(String[] args) {
        List<String> colors = new ArrayList<String>(Arrays.asList("red", "green", "blue", "purple"));
        for (Iterator<String> it = colors.iterator(); it.hasNext(); ) {
            String color = it.next();
            System.out.println(color);
            if (color.equals("green"))
                it.remove();
        }
        System.out.println("At the end, colors = " + colors);
    }
}

/* Outputs:
red
green
blue
purple
At the end, colors = [red, blue, purple]
*/

How would I do this in Python? I can't modify the list while I iterate over it in a for loop because it causes stuff to be skipped (see here). And there doesn't seem to be an equivalent of the Iteratorinterface of Java.

我将如何在 Python 中做到这一点?我在 for 循环中迭代列表时无法修改列表,因为它会导致跳过某些内容(请参阅此处)。并且似乎没有Iterator与 Java的接口等价的东西。

回答by Alex Martelli

Best approach in Python is to make a new list, ideally in a listcomp, setting it as the [:]of the old one, e.g.:

Python 中的最佳方法是创建一个新列表,最好在 listcomp 中,将其设置为[:]旧列表,例如:

colors[:] = [c for c in colors if c != 'green']

NOT colors =as some answers may suggest -- that only rebinds the name and will eventually leave some references to the old "body" dangling; colors[:] =is MUCH better on all counts;-).

不要colors =为一些答案可能暗示-只有重新绑定名字,并最终离开旧的“身体”晃来晃去一些参考; colors[:] =在所有方面都要好得多;-)。

回答by Arkady

Iterate over a copyof the list:

迭代列表的副本

for c in colors[:]:
    if c == 'green':
        colors.remove(c)

回答by del-boy

You could use filter function:

您可以使用过滤功能:

>>> colors=['red', 'green', 'blue', 'purple']
>>> filter(lambda color: color != 'green', colors)
['red', 'blue', 'purple']
>>>

回答by user149513

or you also can do like this

或者你也可以这样做

>>> colors = ['red', 'green', 'blue', 'purple']
>>> if colors.__contains__('green'):
...     colors.remove('green')