python - 在 Python 中检查集合中的项目成员资格

标签 python set

您好,我已经编写了几个月的代码并且了解基础知识,但是我遇到了一个固定的成员资格问题,我找不到解决方案。

我有一个整数对列表列表,我想删除其中包含“a”整数的列表。我认为使用集合是最简单的方法。下面是代码:

## This is the item to test against. 
a = set([3]) 
## This is the list to test.      
groups = [[3, 2], [3, 4], [1, 2], [5, 4], [4, 3]]     

## This is a list that will contain the lists present
## in groups which do not contain "a"
groups_no_a = []        

for group in groups:
    group = set(group)
    if a in group:
        groups_no_a.append(group)
    ## I thought the problem had something to do with
    ## clearing the variable so I put this in,   
    ## but to no remedy. 
    group.clear()  


print groups_no_a 

我也尝试过使用 s.issubset(t) 直到我意识到这测试了 every st 中的元素。

谢谢!

最佳答案

你要测试有没有intersection :

if not a & group:

if not a.intersection(group):

或者反过来,集合是 disjoint :

if a.isdisjoint(group):

方法形式采用any 可迭代,您甚至不必为此将group 变成一个集合。下面的一行代码也可以:

groups_no_a = [group for group in groups if a.isdisjoint(group)]

演示:

>>> a = set([3]) 
>>> groups = [[3, 2], [3, 4], [1, 2], [5, 4], [4, 3]]     
>>> [group for group in groups if a.isdisjoint(group)]
[[1, 2], [5, 4]]

如果您要测试的只是一个元素,那么创建集的性能成本可能会高于您在成员资格测试中获得的性能成本,而只是这样做:

3 not in group

其中 group 是一个短列表。

您可以使用 timeit module比较 Python 代码片段,看看哪种最适合您的特定典型列表大小。

关于python - 在 Python 中检查集合中的项目成员资格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18300554/

相关文章:

c - 从哪里开始用 c 解决这个练习

python - 可以让 Python 生成类似于 bash 的 set -x 的跟踪吗?

Python使用命令行、ghostscript时写入ram文件

python - 断言除了一个键之外两个字典都相等

Python 别名/指针文件创建

clojure - 在clojure中懒惰地构建集合

mysql - MySQL 中的两个表之间是否可以共享一个集合?

python - 如何在 python3 中将组织好的文件放入字典中?

python 3 : clean example for inheritance & abstract methods?

python - Appengine 使用 https 而不是 http