在Java中,我可以使用一个 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]
*/
我该如何用Python实现这个?我无法在for循环迭代列表时修改它,因为这会导致跳过一些元素(请参见此处)。而且似乎没有Java中 Iterator
接口的等价物。