Last active
August 15, 2017 23:25
-
-
Save borland667/65ffe2af333f8c669f439a24c351fef2 to your computer and use it in GitHub Desktop.
Flatten any nested list
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
# Flatten an array in python | |
# | |
# [[1,2,[3]],4] -> [1,2,3,4] | |
# | |
# | |
# Implemented with a recursive generator function | |
# and using yield from syntax from python 3.3 | |
# | |
from collections import Iterable | |
test_data = [[1, 2, [3]], 4, [3, [5, 7, 5, [5, 2]]]] | |
def flatten(data): | |
""" | |
Recursive generator function for any iterable including nested ones | |
""" | |
for x in data: | |
if isinstance(x, Iterable) and not isinstance(x, (str, bytes)): | |
# Delegate generation to the last one | |
# (avoids too many context switches) | |
yield from flatten(x) | |
else: | |
# Actual value | |
yield x | |
if __name__ == "__main__": | |
print(str(list(flatten(test_data)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment