保存所有交点的三个列表的交集? (不是严格的交集)

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

有没有最pythonic(原生)的相交方式

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}

但是我怎样才能得到所有相交的结果呢?

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

严格

非严格

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

结果:

{3, 6, 7, 8}

P.S。 9 & 10 不应该是“非严格”交集的一部分

试试这个:

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}

在此解决方案中,所有项目都被放入一个计数器中,任何被发现多次出现的项目都被放入 results 集合中。

这应该适用于任意数量的集合(不仅仅是三个)。

如果你更喜欢单行而不是循环,试试这个:

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}

这种方法的优点是可以轻松修改以处理更多集,如果您以后决定使用更多的话。

逻辑同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}