简体   繁体   中英

Finding pairs of intersecting sets in a list of arbitrary sets

You have an arbitrary number of sets, for example:

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

You want to see if any value in one set is also in any other set. What is the most efficient way to do this?

Currently I have the following:

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

Which results in:

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

Its a minor tweak but you can let itertools.combinations generate the set pairs for you. This example is python 3 so the representations look a little different, but should work fine in 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}
 set.intersection(*list_of_sets)

将解开集合列表并找到交集。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM