[英]Taking the union of sets
I have a list l
of sets. 我有一个列表l
套。 To take the union of all the sets in l
I do: 为了取得l
中所有集合的联合,我做了:
union = set()
for x in l:
union |= x
I have a feeling there is a more economical/functional way of writing this. 我觉得有一种更经济/更实用的写作方式。 Can I improve upon this? 我能改进吗?
Here's how I would do it (some corrections as per comments): 这是我将如何做(根据评论的一些更正):
union_set = set()
union_set.update(*l)
or 要么
union_set = set.union(*l)
>>> l = [set([1, 2, 3]), set([3, 4, 5]), set([0, 1])]
>>> set.union(*l)
set([0, 1, 2, 3, 4, 5])
If you're looking for a functional approach, there's little more traditional than reduce()
: 如果您正在寻找一种功能性方法,那么传统方法就比reduce()
更为传统:
>>> reduce(set.union, [ set([1,2]), set([3,4]), set([5,6]) ])
set([1, 2, 3, 4, 5, 6])
In Python 3.0, reduce
can be found in the functools module ; 在Python 3.0中,可以在functools模块中找到reduce
; in 2.6 and 2.7, it exists both in functools
and (as in older interpreters) built-in. 在2.6和2.7中,它存在于functools
和内置的(如旧的解释器中)。
union = reduce(set.union, l)
In Python 2.x, reduce
is a built-in. 在Python 2.x中, reduce
是内置的。 In 3.x, it's in the functools
module. 在3.x中,它位于functools
模块中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.