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

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

问题描述

我在玩 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]

解决方案

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

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

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