pythonsetset-union

python merge set of fronzensets into one set


I am trying to merge sets defined in a set and this is what I have now

a = frozenset([1,3,4])
b = frozenset([1,2,3,4,5])
s = set()
s.add(a)
s.add(b)
merged = set(itertools.chain.from_iterable(s))

In practice, s may contain many frozensets. Is there better ways to do it? It feels like a reduce case, but

from functools import reduce
merged = reduce(|, s)

doesn't work.

Also

merged = reduce(set.add, s)

doesn't work because the elements of s are frozensets.


Solution

  • If you have more than two frozensets, create a container (e.g., list) of them and apply a union:

    listoffrozensets = [a,b,...]
    frozenset().union(*listoffrozensets)