Python-多个列表的交集? [英] Python -Intersection of multiple lists?

查看:555
本文介绍了Python-多个列表的交集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python并能够获得两个列表的交集:

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

result = set(a).intersection(b)

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

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

那么结果应该是

[3,4]

推荐答案

对于2.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


对于较新版本的python:


for newer versions of python:

intersection方法接受任意数量的参数

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)

我不太确定哪种方法会更有效,并且感觉这将取决于d[0]的大小和列表的大小,除非python对它进行了内置检查

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

在相交法中.

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

这篇关于Python-多个列表的交集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆