在 Python 中遍历列表时删除元素
问题描述
在 Java 中,我可以使用 Iterator
然后使用 .remove()
迭代器的方法来移除迭代器返回的最后一个元素,像这样:
In Java I can do by using an Iterator
and then using the .remove()
method of the iterator to remove the last element returned by the iterator, like this:
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
接口等效的东西.
How would I do this in Python? I can't modify the list while I iterate over it in a for loop because it causes stuff to be skipped (see here). And there doesn't seem to be an equivalent of the Iterator
interface of Java.
解决方案
遍历列表的副本:
for c in colors[:]:
if c == 'green':
colors.remove(c)
相关文章