2

这是我的代码。

s = set()
for x in [ {1,2}, {3,4}, {5,1} ]:
    s |= x

它返回set([1, 2, 3, 4, 5])

在这种情况下是否可以使用集合理解?我怎样才能写得更短?

4

2 回答 2

9

set.union

set.union(*[{1,2}, {3,4}, {5,1}])
# {1, 2, 3, 4, 5}

Why do you need a loop at all? Use set.union, it lets you compute the union of more than two sets (containers) at a time. I say "containers", because the second (and onwards) arguments need not be sets at all.

set.union(*[{1,2}, [3,4], [5,1]])
# {1, 2, 3, 4, 5}

The first, however, needs to be. Alternatively,

set().union(*[[1,2], [3,4], [5,1]])
# {1, 2, 3, 4, 5}

When calling union on a set object (and not the class), none of the arguments need be sets.


functools.reduce

from functools import reduce

reduce(set.union, [{1,2}, {3,4}, {5,1}])
# {1, 2, 3, 4, 5}

This performs a pairwise reduction, accumulating a result. Not nearly as good as the first option, however.

于 2018-04-13T19:33:40.113 回答
3

如果你真的想要一个集合理解:

lst = [{1,2}, {3,4}, {5,1}]
{elem for set_ in lst for elem in set_}
于 2018-04-13T19:38:22.570 回答