在 Python 中遍历列表时删除元素

发布于 2024-08-02 21:05:50 字数 1151 浏览 5 评论 0原文

在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

花之痕靓丽 2024-08-09 21:05:50

Python 中的最佳方法是创建一个新列表,最好是在 listcomp 中,将其设置为旧列表的 [:] ,例如:

colors[:] = [c for c in colors if c != 'green']

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.:

colors[:] = [c for c in colors if c != 'green']

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;-).

孤千羽 2024-08-09 21:05:50

迭代列表的副本

for c in colors[:]:
    if c == 'green':
        colors.remove(c)

Iterate over a copy of the list:

for c in colors[:]:
    if c == 'green':
        colors.remove(c)
め七分饶幸 2024-08-09 21:05:50

您可以使用过滤功能:

>>> colors=['red', 'green', 'blue', 'purple']
>>> filter(lambda color: color != 'green', colors)
['red', 'blue', 'purple']
>>>

You could use filter function:

>>> colors=['red', 'green', 'blue', 'purple']
>>> filter(lambda color: color != 'green', colors)
['red', 'blue', 'purple']
>>>
时光清浅 2024-08-09 21:05:50

或者你也可以这样做

>>> colors = ['red', 'green', 'blue', 'purple']
>>> if colors.__contains__('green'):
...     colors.remove('green')

or you also can do like this

>>> colors = ['red', 'green', 'blue', 'purple']
>>> if colors.__contains__('green'):
...     colors.remove('green')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文