Python - 多个列表的交叉?

问题描述 投票:46回答:4

我正在玩python并且能够得到两个列表的交集:

result = set(a).intersection(b)

现在,如果d是包含ab以及第三个元素c的列表,是否有内置函数用于查找d中所有三个列表的交集?所以,例如,

d = [[1,2,3,4], [2,3,4], [3,4,5,6,7]]

那么结果应该是

[3,4]
python list set intersection
4个回答
42
投票

对于2.4,您可以只定义交叉函数。

def intersect(*d):
    sets = iter(map(set, d))
    result = sets.next()
    for s in sets:
        result = result.intersection(s)
    return result

对于较新版本的python:

intersection方法采用任意数量的参数

result = set(d[0]).intersection(*d[:1])

或者,您可以将第一个集合与自身相交,以避免切片并制作副本:

result = set(d[0]).intersection(*d)

我不确定哪个更高效,并且感觉它将取决于d[0]的大小和列表的大小,除非python有内置的检查就像

if s1 is s2:
    return s1

在交集方法中。

>>> d = [[1,2,3,4], [2,3,4], [3,4,5,6,7]]
>>> set(d[0]).intersection(*d)
set([3, 4])
>>> set(d[0]).intersection(*d[1:])
set([3, 4])
>>> 

55
投票
set.intersection(*map(set,d))

4
投票

@ user3917838

既简单又简单,但需要一些铸造才能使其工作并给出一个列表作为结果。它应该看起来像:

list(reduce(set.intersection, [set(item) for item in d ]))

哪里:

d = [[1,2,3,4], [2,3,4], [3,4,5,6,7]]

结果是:

[3, 4]

至少在Python 3.4中


1
投票

Lambda减少。

from functools import reduce #you won't need this in Python 2
reduce(set.intersection, [[1, 2, 3, 4], [2, 3, 4], [3, 4, 5, 6, 7]])
© www.soinside.com 2019 - 2024. All rights reserved.