找到多个集合的交集的最佳方法?
我有一个集合列表:
setlist = [s1,s2,s3...]
我想要 s1 ∩ s2 ∩ s3 ...
我可以编写一个函数来通过执行一系列成对的 s1.intersection(s2)
等来完成此操作
。推荐的、更好的还是内置的方式?
I have a list of sets:
setlist = [s1,s2,s3...]
I want s1 ∩ s2 ∩ s3 ...
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
从 Python 2.6 版开始,您可以对
set.intersection() 使用多个参数
,就像如果集合在列表中,这将转换为:
其中
*a_list
是 列表扩展请注意,
set.intersection
不是静态的方法,但这使用函数符号来应用第一个集合与列表其余部分的交集。因此,如果参数列表为空,则会失败。From Python version 2.6 on you can use multiple arguments to
set.intersection()
, likeIf the sets are in a list, this translates to:
where
*a_list
is list expansionNote 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.从 2.6 开始,
set.intersection
接受任意多个可迭代对象。As of 2.6,
set.intersection
takes arbitrarily many iterables.显然
set.intersection
是您想要的,但如果您需要“取所有这些的总和”、“取所有这些的乘积”、“取所有的异或”的概括这些”,您正在寻找的是reduce
函数:或
Clearly
set.intersection
is what you want here, but in case you ever need a generalisation of "take the sum of all these", "take the product of all these", "take the xor of all these", what you are looking for is thereduce
function:or
如果你没有Python 2.6或更高版本,另一种方法是编写一个显式的for循环:
你也可以使用
reduce
:但是,许多Python程序员不喜欢它,包括 Guido 本人:
If you don't have Python 2.6 or higher, the alternative is to write an explicit for loop:
You can also use
reduce
:However, many Python programmers dislike it, including Guido himself:
我相信最简单的做法是:
set4 将是 set1 、 set2 、 set3 的交集,并且包含值 2。
I believe the simplest thing to do is:
set4 will be the intersection of set1 , set2, set3 and will contain the value 2.
在这里,我为多个集合交集提供了一个通用函数,试图利用可用的最佳方法:
Guido 可能不喜欢
reduce
,但我有点喜欢它:)Here I'm offering a generic function for multiple set intersection trying to take advantage of the best method available:
Guido might dislike
reduce
, but I'm kind of fond of it :)Jean-François Fabre set.intesection(*list_of_sets) 答案绝对是最 Pyhtonic 的,并且是正确接受的答案。
对于那些想要使用reduce的人,以下方法也适用:
reduce(set.intersection, list_of_sets)
Jean-François Fabre set.intesection(*list_of_sets) answer is definetly the most Pyhtonic and is rightly the accepted answer.
For those that want to use reduce, the following will also work:
reduce(set.intersection, list_of_sets)