如何在Python中的for循环中删除列表元素? [英] How to remove list elements in a for loop in Python?
问题描述
我有一个清单
a = ["a", "b", "c", "d", "e"]
我想在如下所示的for循环中删除此列表中的元素:
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?
推荐答案
在使用for
循环对其进行迭代时,不允许从列表中删除元素.
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[:] = []
或者,您可以使用while
循环:
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
或者,您可以使用 filter
或列表解析并分配结果返回到a
:
a = filter(lambda item:... , a)
或
a = [item for item in a if ...]
其中...
代表您需要检查的条件.
where ...
stands for the condition that you need to check.
这篇关于如何在Python中的for循环中删除列表元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!