pythonmapdel_How to delete an element from a list while iterating it in Python?

问题

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.

回答1:

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

回答2:

for el in L:

if el == 2:

del L[el]

来源:https://stackoverflow.com/questions/2442651/how-to-delete-an-element-from-a-list-while-iterating-it-in-python

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值