This is my code.
s = set()
for x in [ {1,2}, {3,4}, {5,1} ]:
s |= x
It returns set([1, 2, 3, 4, 5]).
Is it possible to use set comprehension in such a case? How can I write it shorter?
set.unionset.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.reducefrom 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.
If you really want a set comprehension here:
lst = [{1,2}, {3,4}, {5,1}]
{elem for set_ in lst for elem in set_}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With