在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 的接口.