How to unpack a nested list in python to sublists? -
assume list is:
[ [1,2,3,4], [ [[5], [6]], [7] ]]
after unpack, want [1,2,3,4], [5], [6], [7]
how low time complexity?
the linked duplicate flattens iterable completely. need slight tweak make process stop 1 step earlier:
import collections def flattish(l): el in l: if isinstance(el, collections.iterable) , not isinstance(el, str): if any(isinstance(e, collections.iterable) e in el): sub in flattish(el): yield sub else: yield el else: yield [el]
the any(...
check if iterable contains iterables. flatten [1, [2, 3]]
, leave [5]
as-is. additionally, yield [el]
ensures non-iterables contained in list
, result list
contains list
s, of may have single element.
Comments
Post a Comment