在python中获取Nmany列表的交集

2024-04-19 09:44:00 发布

您现在位置:Python中文网/ 问答频道 /正文

在python中获取N-many列表的交集最简单的方法是什么?在

如果我有两个列表a和b,我知道我可以:

a = set(a)
b = set(b)
intersect = a.intersection(b)

但我想做点像a&b&c&d&;d&a&b&c&d&。。。对于任意一组列表(理想情况下不需要先转换为集合,但如果这是最简单/最有效的方法,我可以处理它。)

也就是说,我想写一个函数intersect(*args),它可以有效地处理任意多个集合。最简单的方法是什么?在

编辑:我自己的解决方案是减少(集合交集,[a,b,c])——这样好吗?在

谢谢。在


Tags: 方法函数编辑列表情况args解决方案many
3条回答

这适用于一个或多个列表。“0列表”的情况并不容易,因为它必须返回一个包含所有可能值的集合。在

def intersection(first, *others):
    return set(first).intersection(*others)

这适用于一个或多个列表,并且不使用多个参数:

>>> def intersection(*listas):
...     return set(listas[0]).intersection(*listas[1:]) 
...     
>>> intersection([1,2,3,4],[4,5,6],[2,4,5],[1,4,8])
set([4])
>>> intersection([1,2,3,4])
set([1, 2, 3, 4])
>>> 

无论如何,我不确定这比其他答案好。在

lists = [[5,4,3], [4,2], [6,2,3,4]]

try:
    # the following line makes one intersection too much, but I don't think
    # this hurts performance noticably.
    intersected = set(lists[0]).intersection(*lists)
except ValueError:
    # no lists[0]
    intersected = set()

print intersected         # set([4])

集合可以与任何iterable相交,不需要先将其转换为集合。在

相关问题 更多 >