python集合可以修改吗_如何通过就地过滤来修改python集合?

I was wondering, if there is way in Python to modify collections without creating new ones. E.g.:

lst = [1, 2, 3, 4, 5, 6]

new_lst = [i for i in lst if i > 3]

Works just fine, but a new collection is created. Is there a reason, that Python collections lack a filter() method (or similar) that would modify the collection object in place?

解决方案

The other answers are correct; if you want all the names pointing to the old list to point to the new list you can use slice assignment.

However, that's not truly in-place creation; the new list is first created elsewhere. The link in Sven's answer is good.

The reason there isn't one that truly operates in-place is that while making a new list like that is O(n), each truly in-place item removal would be O(k) by itself, where k is the length of the list from the removal point on. The only way to avoid that with Python lists is to use some temporary storage, which is what you're doing by using slice assignment.

An example of an in-place O(n) filter on a collections.deque, in case you don't need to store your data in a list:

from collections import deque

def dequefilter(deck, condition):

for _ in xrange(len(deck)):

item = deck.popleft()

if condition(item):

deck.append(item)

deck = deque((1, 2, 3, 4, 5))

dequefilter(deck, lambda x: x > 2) # or operator.gt(2)

print deck

# deque([3, 4, 5])

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值