在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
接口等价的接口。
可以使用筛选函数:
Python中最好的方法是创建一个新列表,最好是在listcomp中,将其设置为旧列表的
[:]
,例如:而不是像某些答案可能暗示的那样
colors =
——只是重新绑定名称,最终会留下一些对旧“body”的引用;在所有方面colors[:] =
都要好得多;-)。迭代列表的副本:
相关问题 更多 >
编程相关推荐