在 Python 中遍历列表时删除元素[重复]
-
20-09-2019 - |
题
这个问题在这里已经有答案了:
- 如何在迭代时从列表中删除项目? 26 个答案
在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 循环中迭代列表时,我无法修改列表,因为它会导致跳过某些内容(请参阅 这里)。而且似乎没有相当于 Iterator
Java 的接口。
解决方案
迭代一个 复制 名单中:
for c in colors[:]:
if c == 'green':
colors.remove(c)
其他提示
Python 中的最佳方法是创建一个新列表,最好是在 listcomp 中,将其设置为 [:]
旧的,例如:
colors[:] = [c for c in colors if c != 'green']
不是 colors =
正如一些答案可能暗示的那样——这只会重新绑定名称,最终会留下一些对旧“主体”的引用悬而未决; colors[:] =
在所有方面都好得多;-)。
您可以使用过滤功能:
>>> colors=['red', 'green', 'blue', 'purple']
>>> filter(lambda color: color != 'green', colors)
['red', 'blue', 'purple']
>>>
或者你也可以这样做
>>> colors = ['red', 'green', 'blue', 'purple']
>>> if colors.__contains__('green'):
... colors.remove('green')
不隶属于 StackOverflow