相关疑难解决方法(0)

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

在Java中我可以通过使用a Iterator然后使用.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]
*/
Run Code Online (Sandbox Code Playgroud)

我将如何在Python中执行此操作?我在for循环中迭代它时无法修改列表,因为它会导致跳过东西(参见此处).并且似乎没有相当于IteratorJava 的接口.

python iterator loops list python-datamodel

11
推荐指数
3
解决办法
1万
查看次数

标签 统计

iterator ×1

list ×1

loops ×1

python ×1

python-datamodel ×1