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

2024-07-08 16:12:31 发布

您现在位置:Python中文网/ 问答频道 /正文

在Java中,我可以使用^{},然后使用迭代器的^{}方法删除迭代器返回的最后一个元素,如下所示:

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]
*/

在Python中我该怎么做?当我在for循环中遍历列表时,我不能修改它,因为它会导致跳过内容(请参见here)。而且似乎没有一个与Java的Iterator接口等价的接口。


Tags: forstringitgreenblueredjavapublic
3条回答

可以使用筛选函数:

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

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

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

而不是像某些答案可能暗示的那样colors =——只是重新绑定名称,最终会留下一些对旧“body”的引用;在所有方面colors[:] =都要好得多;-)。

迭代列表的副本:

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

相关问题 更多 >

    热门问题