Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #101298

Re: How to union nested Sets / A single set from nested sets?

From Peter Otten <__peter__@web.de>
Newsgroups comp.lang.python
Subject Re: How to union nested Sets / A single set from nested sets?
Date 2016-01-06 14:39 +0100
Organization None
Message-ID <mailman.27.1452087583.2305.python-list@python.org> (permalink)
References <bd94920f139af986c1a304f5ce844f9d@kapsi.fi>

Show all headers | View raw


mviljamaa wrote:

> I'm forming sets by set.adding to sets and this leads to sets such as:
> 
> Set([ImmutableSet(['a', ImmutableSet(['a'])]), ImmutableSet(['b',
> 'c'])])
> 
> Is there way union these to a single set, i.e. get
> 
> Set(['a', 'b', 'c'])
> 
> ?

1 What version of Python are you working with?

Both Python 2.7 and 3.x have built-in set and frozenset types that you 
should use.

2 Instead of flattening the nested data I recommend that you avoid nesting 
in the first place by using update() instead of add()

>>> x = {"a", "b"}
>>> y = {"b", "c"}
>>> z = {"a", "c", "d"}
>>> result = set()
>>> for subset in x, y, z:
...     result.update(subset) #  or: result |= subset
... 
>>> result
{'b', 'a', 'd', 'c'}

For a fixed number of subsets you can avoid the loop and write

>>> result = set()
>>> result.update(x, y, z)
>>> result
{'b', 'a', 'd', 'c'}

or

>>> x | y | z
{'b', 'a', 'd', 'c'}

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: How to union nested Sets / A single set from nested sets? Peter Otten <__peter__@web.de> - 2016-01-06 14:39 +0100

csiph-web