Last active
July 10, 2017 15:19
-
-
Save tomschr/e67b4ad75dc1349d7ed1ae2dc5ae5518 to your computer and use it in GitHub Desktop.
Flatten nested list with unlimited depth
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections.abc import Iterable | |
def flatten(items, ltypes=Iterable): | |
"""flatten(sequence) -> list | |
Returns a single, flat list which contains all elements retrieved from the sequence | |
""" | |
if not isinstance(items, list): | |
yield items | |
stack = [iter(items)] | |
while stack: | |
for item in stack[-1]: | |
if isinstance(item, ltypes): | |
stack.append(iter(item)) | |
break | |
yield item | |
else: | |
stack.pop() | |
def flatten2(input, ltypes=(list,tuple)): | |
ltype = type(input) | |
output = [] | |
stack = [] | |
stack.extend(reversed(input)) | |
while stack: | |
top = stack.pop() | |
if isinstance(top, ltypes): | |
stack.extend(reversed(top)) | |
else: | |
output.append(top) | |
return ltype(output) | |
def flatten3(l, ltypes=(list, tuple)): | |
ltype = type(l) | |
l = list(l) | |
i = 0 | |
while i < len(l): | |
while isinstance(l[i], ltypes): | |
if not l[i]: | |
l.pop(i) | |
i -= 1 | |
break | |
else: | |
l[i:i + 1] = l[i] | |
i += 1 | |
return ltype(l) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment