Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 882
nos Avatar asked Feb 09 '17 20:02

nos


People also ask

How do you combine sets in Python?

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 (*).

How do you convert a Frozenset to a list?

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.

What is difference between set and Frozenset in Python?

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.

How do you convert a set to Frozenset in Python?

Python frozenset() Function The frozenset() function returns an unchangeable frozenset object (which is like a set object, only unchangeable).


2 Answers

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)
like image 73
DYZ Avatar answered Oct 20 '22 14:10

DYZ


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})
like image 44
juanpa.arrivillaga Avatar answered Oct 20 '22 13:10

juanpa.arrivillaga