Created
March 7, 2017 00:05
-
-
Save lukasz-madon/8a707a6ae3968d3c41eda3dbede7a079 to your computer and use it in GitHub Desktop.
Flatten python collection
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
# following code uses recursion, so it may run out of stack memeory for large collections | |
def flatten(container): | |
"""generate a flatten sequence from the input list""" | |
for i in container: | |
if isinstance(i, (list, tuple)): | |
for j in flatten(i): | |
yield j | |
else: | |
yield i | |
print list(flatten([])) == [] | |
print list(flatten([[1 ,2, [3]], 4])) == [1, 2, 3, 4] | |
print list(flatten([1, 2, [3, 4, [5], [34]], [6, [[[7, 89]]]]])) == [1, 2, 3, 4, 5, 34, 6, 7, 89] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment