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.
Sets can be combined in python using different functions. There are functions such as union(), update() and reduce() for joining two sets. We can also combine two sets using bitwise operators such as the union operator (|) and the unpacking operator (*).
Python frozenset object is an immutable unordered collection of data elements. Therefore, you cannot modify the elements of the frozenset. To convert this set into a list, you have to use the list function and pass the set as a parameter to get the list object as an output.
Frozen set is just an immutable version of a Python set object. While elements of a set can be modified at any time, elements of the frozen set remain the same after creation. Due to this, frozen sets can be used as keys in Dictionary or as elements of another set.
Python frozenset() Function The frozenset() function returns an unchangeable frozenset object (which is like a set object, only unchangeable).
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)
You can use reduce, just use the appropriate function:
>>> from functools import reduce
>>> frozenset.union
<method 'union' of 'frozenset' objects>
>>> reduce(frozenset.union, [a,b])
frozenset({1, 2, 3, 4, 5})
>>>
You were on the right track with |
, but |
is an operator in Python, and can't be substituted for a function. But when you want to do that, import the operator!
>>> import operator
>>> reduce(operator.or_, [a,b])
frozenset({1, 2, 3, 4, 5})
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