John Smith
John Smith

Reputation: 33

Python - Comparing two lists of sets

I have two lists:

list1 = [
    set(['3105']),
    set(['3106', '3107']),
    set(['3115']),
    set(['3122']),
    set(['3123', '3126', '286'])
]

and

list2 = [
    set(['400']),
    set(['3115']),
    set(['3100']),
    set(['3107']),
    set(['3123', '3126'])
]

How do I compare the intersection of these lists, so, for example, if 3126 is somewhere in any of the sets of both lists, it will append another list with 3126. My end goal is to append a separate list and then take the length of the list so I know how many matches are between lists.

Upvotes: 2

Views: 2507

Answers (3)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251186

>>> common_items = set().union(*list1) & set().union(*list2)
>>> common_items
set(['3123', '3115', '3107', '3126'])
>>> '3126' in common_items
True

Timing comparisons:

>>> %timeit reduce(set.union, list1) & reduce(set.union, list2)
100000 loops, best of 3: 11.7 us per loop
>>> %timeit set().union(*list1) & set().union(*list2)      #winner
100000 loops, best of 3: 4.63 us per loop
>>> %timeit set(s for x in list1 for s in x) & set(s for x in list2 for s in x)
10000 loops, best of 3: 11.6 us per loop
>>> %timeit import itertools;set(itertools.chain.from_iterable(list1)) & set(itertools.chain.from_iterable(list2))
100000 loops, best of 3: 9.91 us per loop

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1125138

You'd have to merge all sets; take the unions of the sets in both lists, then take the intersection of these two unions:

sets_intersection = reduce(set.union, list1) & reduce(set.union, list2)

if 3126 in sets_intersection:
    # ....

Upvotes: 2

jh314
jh314

Reputation: 27812

You can flatten the two lists of sets into sets:

l1 = set(s for x in list1 for s in x)
l2 = set(s for x in list2 for s in x)

Then you can compute the intersection:

common = l1.intersection(l2)  # common will give common elements
print len(common) # this will give you the number of elements in common.

Results:

>>> print common
set(['3123', '3115', '3107', '3126'])
>>> len(common)
4

Upvotes: 0

Related Questions