在Python中求N个列表的交集

7 投票
3 回答
5470 浏览
提问于 2025-04-15 23:25

在Python中,最简单的方法是什么来找出多个列表的交集?

如果我有两个列表a和b,我知道可以这样做:

a = set(a)
b = set(b)
intersect = a.intersection(b)

但是我想做的是像这样 a & b & c & d & ... 处理任意数量的列表(理想情况下不需要先转换成集合,但如果那是最简单或最高效的方法,我也能接受)。

也就是说,我想写一个函数 intersect(*args),可以高效地处理任意数量的集合。最简单的方法是什么呢?

补充:我自己的解决方案是 reduce(set.intersection, [a,b,c]) -- 这样好吗?

谢谢。

3 个回答

2
lists = [[5,4,3], [4,2], [6,2,3,4]]

try:
    # the following line makes one intersection too much, but I don't think
    # this hurts performance noticably.
    intersected = set(lists[0]).intersection(*lists)
except ValueError:
    # no lists[0]
    intersected = set()

print intersected         # set([4])

集合可以和任何可迭代的东西进行交集运算,不需要先把它转换成集合。

3

这个方法可以处理一个或多个列表,而且不需要用到多个参数:

>>> def intersection(*listas):
...     return set(listas[0]).intersection(*listas[1:]) 
...     
>>> intersection([1,2,3,4],[4,5,6],[2,4,5],[1,4,8])
set([4])
>>> intersection([1,2,3,4])
set([1, 2, 3, 4])
>>> 

我不太确定这个方法是否比其他答案更好,不过无论如何就是这样。

14

这个方法适用于一个或多个列表。如果是0个列表的情况就比较复杂,因为它需要返回一个包含所有可能值的集合。

def intersection(first, *others):
    return set(first).intersection(*others)

撰写回答