如何在Python中迭代时从列表中删除元素? [英] How to delete an element from a list while iterating it in Python?

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

问题描述

假设我有一个数字列表:

L = [1, 2, 3, 4, 5]

如何在迭代时从列表中删除一个元素,比如说 3?

我尝试了以下代码,但没有成功:

 for el in L:如果 el == 3:德尔

有什么想法吗?

谢谢,博达·西多.

解决方案

通常最好是建设性地进行——建立你想要的项目的新列表,而不是删除你不需要的项目.例如:

L[:] = [el for el in L if el != 3]

列表推导式构建所需的列表并将分配给整个列表切片",L[:],确保您只是重新绑定名称,但完全替换内容,因此效果与您想要执行的删除"完全相同.这也很快.

如果您绝对不惜任何代价必须进行删除操作,那么一种微妙的方法可能会奏效:

<预><代码>>>>德尔 = 0>>>对于 i, el 在 enumerate(list(L)):...如果 el==3:... del L[i-ndel]... ndel += 1

没有任何地方像 listcomp 方法那样优雅、干净、简单或性能良好,但它确实可以胜任(尽管乍一看它的正确性并不明显,实际上我在编辑之前就错了!-).不惜一切代价"适用于此处;-)

循环使用索引代替项目是另一种较差但可行的方法,用于必须删除"的情况——但请记住在这种情况下反转索引...:

for i in reversed(range(len(L))):如果 L[i] == 3:del L[i]

确实,这是 reversed 的一个主要用例,当我们讨论是否添加该内置函数时 - reversed(range(... is't 在没有 reversed 的情况下很容易获得,并且以相反的顺序在列表上循环有时很有用.替代

for i in range(len(L) - 1, -1, -1):

真的很容易出错;-)

不过,我在本答案开头推荐的 listcomp 在检查替代方案时看起来越来越好,不是吗?-)

Suppose I have a list of numbers:

L = [1, 2, 3, 4, 5]

How do I delete an element, let's say 3, from the list while I iterate it?

I tried the following code but it didn't do it:

for el in L:
  if el == 3:
    del el

Any ideas?

Thanks, Boda Cydo.

解决方案

Best is usually to proceed constructively -- build the new list of the items you want instead of removing those you don't. E.g.:

L[:] = [el for el in L if el != 3]

the list comprehension builds the desired list and the assignment to the "whole-list slice", L[:], ensure you're not just rebinding a name, but fully replacing the contents, so the effects are identically equal to the "removals" you wanted to perform. This is also fast.

If you absolutely, at any cost, must do deletions instead, a subtle approach might work:

>>> ndel = 0
>>> for i, el in enumerate(list(L)):
...    if el==3:
...      del L[i-ndel]
...      ndel += 1

nowhere as elegant, clean, simple, or well-performing as the listcomp approach, but it does do the job (though its correctness is not obvious at first glance and in fact I had it wrong before an edit!-). "at any cost" applies here;-).

Looping on indices in lieu of items is another inferior but workable approach for the "must do deletions" case -- but remember to reverse the indices in this case...:

for i in reversed(range(len(L))):
  if L[i] == 3: del L[i]

indeed this was a primary use case for reversed back when we were debating on whether to add that built-in -- reversed(range(... isn't trivial to obtain without reversed, and looping on the list in reversed order is sometimes useful. The alternative

for i in range(len(L) - 1, -1, -1):

is really easy to get wrong;-).

Still, the listcomp I recommended at the start of this answer looks better and better as alternatives are examined, doesn't it?-).

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

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