[Python-ideas] Proposal: flatten multi-nested list/tuple/set and other certain class/type.
gey3933 at gmail.com
Thu Apr 12 02:26:49 EDT 2018
I thought that itertools.chain.from_iterable isn't useful.
cuz this only allow "single-nested iterable -- this will raise error when
arg has non-nested element--" like below::
>>> from itertools import chain
<itertools.chain object at 0x00000112D332BF98>
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
and this can't unpack over double nest.
>>> chain.from_iterable([[[1, 2]], [[4, 5]]])
<itertools.chain object at 0x00000112D3330B00>
[[1, 2], [4, 5]]
So, I wanted to make "True chain.from_iterable". and this is it.
def flatten(iterables, unpack=(list, tuple, set), peep=(list, tuple, set)):
for element in iterables:
if isinstance(element, unpack):
if isinstance(element, peep):
yield from flatten(element, unpack=unpack, peep=peep)
yield from flatten(element, unpack=(), peep=())
elif isinstance(element, peep):
yield type(element)(flatten(element, unpack=unpack, peep=peep))
Reason why I didin't use type() is wanted to unpack type-object like "range"
and I wanted to unpack user-defined-class/func. this is why I didin't use
collections.Iterable to check instance.
I know this will be destructed by itertools.count :(
Please give me advice.
And I wanna know why function like this is not in standard library.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-ideas