我正在玩python并且能够得到两个列表的交集:
result = set(a).intersection(b)
现在,如果d
是包含a
和b
以及第三个元素c
的列表,是否有内置函数用于查找d
中所有三个列表的交集?所以,例如,
d = [[1,2,3,4], [2,3,4], [3,4,5,6,7]]
那么结果应该是
[3,4]
对于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])
>>>
set.intersection(*map(set,d))
@ 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中
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]])