gpt4 book ai didi

python - 如果项目在一个或两个(或 N 个)其他列表中,如何从列表中删除该项目

转载 作者:太空宇宙 更新时间:2023-11-03 12:57:00 24 4
gpt4 key购买 nike

我有一个名为 parent_list 的父列表,以及两个用于过滤 parent_list 的子集。这些子集也是 Python 列表,它们被称为 filter1filter2

我能做吗:

final_list = [object for object in parent_list if object.pk not in filter1 or filter2]

或者我是否需要单独执行此过滤,如:

intermediate_list = [object for object in parent_list if object.pk not in filter1]
final_list = [object for object in intermediate_list if object.pk not in filter2]

我无法从有关 python 列表推导的文档中明确找到答案。

最佳答案

使用集合快速查找项目:

final_list = [object for object in parent_list if object.pk not in set(filter1 + filter2)]
# ^

随着从集合中删除重复项目,整个搜索空间的大小也减少了。

找到这个 somewhere所以:

Sets are implemented using hash tables. Whenever you add an object to a set, the position within the memory of the set object is determined using the hash of the object to be added. When testing for membership, all that needs to be done is basically to look if the object is at the position determined by its hash, so the speed of this operation does not depend on the size of the set. For lists, in contrast, the whole list needs to be searched, which will become slower as the list grows.

关于python - 如果项目在一个或两个(或 N 个)其他列表中,如何从列表中删除该项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37867126/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com