pop在python中的用法,使用pop()在Python中进行列表操作

本文探讨了在Python中如何避免使用pop导致索引变化的问题,介绍了一种通过列表推导式或生成器来同时删除多个元素的方法,适用于不同规模的数据处理。针对大型列表,推荐使用惰性过滤器ifilter,而对于内存消耗敏感的情况,可以利用生成器实现轻量级操作。
摘要由CSDN通过智能技术生成

In short, I need to remove multiple items from a list according to their indexes. However, I can't use pop because it shifts the indexes (without some clumsy compensating system). Is there a way to remove multiple items simultaneously?

I have an algorithm that goes through a list, and if the conditions are right removes that item via the pop method. A problem arises seeing as this is all done in a loop. Once pop is done the list is shortened by one, displacing all the values by one. So the loop will go out of range. Is it possible to remove multiple items simultaneously, or another solution?

An example of my problem:

L = ['a', 'b', 'c', 'd']

for i in range(len(L)):

print L

if L[i] == 'a' or L[i] == 'c':

L.pop(i)

解决方案

Are your lists large? If so, use ifilter from itertools to filter out elements that you don't want lazily (with no up front cost).

Lists not so large? Just use a list comprehension:

newlist = [x for x in oldlist if x not in ['a', 'c'] ]

This will create a new copy of the list. This is not generally an issue for efficiency unless you really care about memory consumption.

As a happy medium of syntax convenience and laziness ( = efficiency for large lists), you can construct a generator rather than a list by using ( ) instead of [ ]:

interestingelts = (x for x in oldlist if x not in ['a', 'c'])

After this, you can iterate over interestingelts, but you can't index into it:

for y in interestingelts: # ok

print y

print interestingelts[0] # not ok: generator allows sequential access only

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值