如何通过就地过滤来修改python集合? [英] How to modify python collections by filtering in-place?

查看:86
本文介绍了如何通过就地过滤来修改python集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,Python中是否有方法可以在不创建新集合的情况下修改集合。例如:

  lst = [1、2、3、4、5、6] 
new_lst = [i for如果我> 3]

工作正常,但是会创建一个新集合。 $ p $ b

filter()方法(或类似方法)来修改集合对象?

解决方案

其他答案正确。如果您希望所有指向旧列表的名称都指向新列表,则可以使用切片分配。



但是,这并不是真正的就地创建;新列表首先在其他位置创建。 Sven的答案中的链接很好。



原因没有真正可就地操作的是在制作新列表时像是O(n),则每个真正就地删除的项目本身就是O(k) ,其中 k 是从删除点开始的列表。使用Python列表避免这种情况的唯一方法是使用一些临时存储,这就是通过使用切片分配来完成的工作。



就地示例如果您不需要将数据存储在列表 collections.deque 进行O(n)过滤>:

 从集合中导入deque 

def dequefilter(deck,condition):
对于_ in xrange(len(deck)):
item = deck.popleft()
if condition(item):
eck.append(item)

deck = deque((1、2、3、4、5))
dequefilter(deck,lambda x:x> 2)#或operator.gt(2)
print deck
#deque([3,4,5])


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])

这篇关于如何通过就地过滤来修改python集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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