在任意集的列表中查找成对的交叉集

时间:2016-02-28 23:23:11

标签: python python-2.7

您有任意数量的集合,例如:

sets = [{1,2,3}, {3,4,5}, {5,6,7}]

您想要查看一个集合中的任何值是否也在任何其他集合中。最有效的方法是什么?

目前我有以下内容:

index = 0
for set in sets:
    for i in range(index + 1, len(sets)):
        print set, sets[i], set & sets[i]
    index += 1

结果是:

set([1, 2, 3]) set([3, 4, 5]) set([3])
set([1, 2, 3]) set([5, 6, 7]) set([])
set([3, 4, 5]) set([5, 6, 7]) set([5])

2 个答案:

答案 0 :(得分:2)

这是一个小调整,但您可以让itertools.combinations为您生成集合对。这个例子是python 3所以表示看起来有点不同,但应该在2.x

中正常工作
>>> import itertools
>>> sets = [{1,2,3}, {3,4,5}, {5,6,7}]
>>> for s1,s2 in itertools.combinations(sets,2):
...     print(s1, s2, s1 & s2)
... 
{1, 2, 3} {3, 4, 5} {3}
{1, 2, 3} {5, 6, 7} set()
{3, 4, 5} {5, 6, 7} {5}

答案 1 :(得分:-1)

 set.intersection(*list_of_sets)

将解压缩集合列表并查找交集。

相关问题