且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python - 多个列表的交集?

更新时间:2023-10-22 14:05:58

对于2.4,你可以只定义一个交集函数.

def intersect(*d):集合 = iter(map(set, d))结果 = set.next()对于 s 集合:结果 = result.intersection(s)返回结果


对于较新版本的python:

交集方法接受任意数量的参数

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

或者,您可以将第一个集合与其自身相交以避免对列表进行切片和复制:

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

我不确定哪个更有效,并且感觉这取决于 d[0] 的大小和列表的大小,除非 python 有内置检查因为喜欢

如果 s1 是 s2:返回 s1

在交集方法中.


I am playing with python and am able to get the intersection of two lists:

result = set(a).intersection(b)

Now if d is a list containing a and b and a third element c, is there an built-in function for finding the intersection of all the three lists inside d? So for instance,

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

then the result should be

[3,4]

for 2.4, you can just define an intersection function.

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


for newer versions of python:

the intersection method takes an arbitrary amount of arguments

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

alternatively, you can intersect the first set with itself to avoid slicing the list and making a copy:

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

I'm not really sure which would be more efficient and have a feeling that it would depend on the size of the d[0] and the size of the list unless python has an inbuilt check for it like

if s1 is s2:
    return s1

in the intersection method.

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