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 chain.from_iterable()
<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: try: if isinstance(element, unpack): if isinstance(element, peep): yield from flatten(element, unpack=unpack, peep=peep) else: yield from flatten(element, unpack=(), peep=()) elif isinstance(element, peep): yield type(element)(flatten(element, unpack=unpack, peep=peep)) else: raise TypeError except TypeError: yield element
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.