user12993750
user12993750

Reputation:

Intersection of three lists with saving all intersections? (not strict intersection)

Is there the most pythonic (native) way to intersect

A = {1,2,3,6,7}
B = {3,4,5,7,8}
C = {6,7,8,9,10}

# strict intersection ALL THREE sets
print(A & B & C)
>>> {7}

but how I can get ALL results that were intersected?

>>> {3,6,7,8}

strict

enter image description here

non-strict

enter image description here

Upvotes: 0

Views: 45

Answers (3)

J-L
J-L

Reputation: 1901

Try this:

from collections import Counter

A = {1,2,3,6,7}
B = {3,4,5,7,8}
C = {6,7,8,9,10}

result = set()
for k,v in Counter(list(A) + list(B) + list(C)).items():
    if v > 1:
        result.add(k)

print(result)  # prints:  {3, 4, 5, 7, 8}

In this solution, all items are placed into a counter, and any item that was found to appear more than once is placed in the results set.

This should work on any number of sets (not just three).

If you prefer a one-liner instead of a loop, try this:

from itertools import chain
from collections import Counter

A = {1,2,3,6,7}
B = {3,4,5,7,8}
C = {6,7,8,9,10}

result = {k for k,v in Counter(chain(A,B,C)).items() if v > 1}

print(result)  # prints:  {3, 4, 5, 7, 8}

The advantage of this approach is that it is easily modifiable to handle more sets, should you decide to use more later.

Upvotes: 1

Pygirl
Pygirl

Reputation: 13349

The logic is same as J-L:

from itertools import chain
import collections
a = list(chain.from_iterable([A,B,C]))
y = [item for item, count in collections.Counter(a).items() if count > 1]
set(y)

{3, 6, 7, 8}

Upvotes: 1

rdas
rdas

Reputation: 21275

A = {1,2,3,6,7}
B = {3,4,5,7,8}
C = {6,7,8,9,10}

print((A & B) | (B & C) | (C & A))

Result:

{3, 6, 7, 8}

P.S. 9 & 10 should not be part of the "non-strict" intersection

Upvotes: 3

Related Questions