在Python中遍历列表时移除元素
在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循环遍历列表的时候修改它,因为这样会导致一些元素被跳过(具体可以看这里)。而且Python似乎没有类似Java的Iterator
接口。
4 个回答
5
你可以使用过滤函数:
>>> colors=['red', 'green', 'blue', 'purple']
>>> filter(lambda color: color != 'green', colors)
['red', 'blue', 'purple']
>>>
30
在Python中,最好的做法是创建一个新的列表,最好是在列表推导式中,把它设置为旧列表的[:]
,比如:
colors[:] = [c for c in colors if c != 'green']
不要使用colors =
,虽然有些回答可能会这样建议——这只是重新绑定了名字,最终会留下对旧“内容”的一些引用;而使用colors[:] =
在各方面都要好得多;-).
25
遍历列表的副本:
for c in colors[:]:
if c == 'green':
colors.remove(c)