python - Convert nested iterables to list -
is there easy way in python (using itertools, or otherwise) convert nested iterable f
corresponding list or tuple? i'd save f
can iterate on multiple times, means if nested elements of f
generators, i'll in trouble.
i'll give example input/output.
>>> g = iter(range(2)) >>> my_input = [1, [2, 3], ((4), 5), [6, g]] >>> magical_function(my_input) [1, [2, 3], [[4], 5], [6, [0, 1]]]
it fine if output consisted of tuples, too. issue iterating on g
"consumes" it, can't used again.
this seems best checking if each element iterable, , calling recursive function on if iterable. quick draw-up, try like:
import collections g = iter(range(2)) my_input = [1, [2, 3], ((4), 5), [6, g]] def unfold(iterable): ret = [] element in iterable: if isinstance(element, collections.iterable): ret.append(unfold(element)) else: ret.append(element) return ret n = unfold(my_input) print(n) print(n)
which returns
$ python3 so.py [1, [2, 3], [4, 5], [6, [0, 1]]] [1, [2, 3], [4, 5], [6, [0, 1]]]
it's not prettiest way, , can find ways improve (it puts in list instead of preserving tuples), here general idea use.
Comments
Post a Comment