在 Python 中遍历列表时删除元素
在Java中,我可以使用 Iterator< /code>
然后使用
.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
接口等效的东西。
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]
*/
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Python 中的最佳方法是创建一个新列表,最好是在 listcomp 中,将其设置为旧列表的
[:]
,例如:NOT
colors =
作为一些答案可能会建议——这只会重新绑定名称,最终会留下一些对旧“主体”的引用悬而未决;colors[:] =
在所有方面都更好;-)。Best approach in Python is to make a new list, ideally in a listcomp, setting it as the
[:]
of the old one, e.g.:NOT
colors =
as some answers may suggest -- that only rebinds the name and will eventually leave some references to the old "body" dangling;colors[:] =
is MUCH better on all counts;-).迭代列表的副本:
Iterate over a copy of the list:
您可以使用过滤功能:
You could use filter function:
或者你也可以这样做
or you also can do like this