如何通过就地过滤来修改python集合?

编程入门 行业动态 更新时间:2024-10-07 04:24:03
本文介绍了如何通过就地过滤来修改python集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

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

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

解决方案

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

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

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

就地示例如果您不需要将数据存储在列表:

从集合中导入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集合?

本文发布于:2023-11-30 15:31:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650517.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!