找到多组交集的最佳方法?

2022-01-17 00:00:00 python set set-intersection

问题描述

我有一个集合列表:

setlist = [s1,s2,s3...]

我想要 s1 ∩ s2 ∩ s3 ...

I want s1 ∩ s2 ∩ s3 ...

我可以编写一个函数来执行一系列成对的s1.intersection(s2)

I can write a function to do it by performing a series of pairwise s1.intersection(s2), etc.

有推荐的、更好的或内置的方法吗?

Is there a recommended, better, or built-in way?


解决方案

从 Python 2.6 版开始,您可以使用多个参数来 set.intersection(),如

From Python version 2.6 on you can use multiple arguments to set.intersection(), like

u = set.intersection(s1, s2, s3)

如果集合在列表中,则转换为:

If the sets are in a list, this translates to:

u = set.intersection(*setlist)

其中 *a_list 是 列表扩展

请注意,set.intersection 不是静态方法,但它使用函数符号来应用第一个集合与列表其余部分的交集.因此,如果参数列表为空,这将失败.

Note that set.intersection is not a static method, but this uses the functional notation to apply intersection of the first set with the rest of the list. So if the argument list is empty this will fail.

相关文章