如何在 Python 的 for 循环中删除列表元素? [英] How to remove list elements in a for loop in Python?

查看:50
本文介绍了如何在 Python 的 for 循环中删除列表元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个清单

a = [a"、b"、c"、d"、e"]

我想在如下的 for 循环中删除此列表中的元素:

 用于 a 中的项目:打印(项目)a.删除(项目)

但它不起作用.我能做什么?

解决方案

在使用 for 循环迭代列表时,不允许从列表中删除元素.

重写代码的最佳方式取决于您要尝试做什么.

例如,您的代码相当于:

 用于 a 中的项目:打印(项目)[:] = []

或者,您可以使用 while 循环:

while a:打印(a.pop(0))

<块引用>

我正在尝试删除符合条件的项目.然后我去下一个项目.

您可以将与条件匹配的每个元素复制到第二个列表中:

result = []对于 a 中的项目:如果条件为假:结果.附加(项目)a = 结果

或者,您可以使用 filter 或一个列表推导式并将结果分配回 a:

a = filter(lambda item:... , a)

a = [item for item in a if ...]

其中 ... 代表您需要检查的条件.

I have a list

a = ["a", "b", "c", "d", "e"]

I want to remove elements in this list in a for loop like below:

for item in a:
    print(item)
    a.remove(item)

But it doesn't work. What can I do?

解决方案

You are not permitted to remove elements from the list while iterating over it using a for loop.

The best way to rewrite the code depends on what it is you're trying to do.

For example, your code is equivalent to:

for item in a:
    print(item)
a[:] = []

Alternatively, you could use a while loop:

while a:
    print(a.pop(0))

I'm trying to remove items if they match a condition. Then I go to next item.

You could copy every element that doesn't match the condition into a second list:

result = []
for item in a:
    if condition is False:
        result.append(item)
a = result

Alternatively, you could use filter or a list comprehension and assign the result back to a:

a = filter(lambda item:... , a)

or

a = [item for item in a if ...]

where ... stands for the condition that you need to check.

这篇关于如何在 Python 的 for 循环中删除列表元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆