Created
January 29, 2017 22:24
-
-
Save ahopkins/b9db7cc80f055a483c035b46cbcb304f to your computer and use it in GitHub Desktop.
Recursively flatten an arbitrary number of nested iterators.
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
l = [1, 2, 3, [4, 5, 6, [9, 8, 7, [12, 11, 10], 13, 14], 15, 16], 17, 18] | |
def flatten(input): | |
""" Flatten nested iterators. Looks specifically for lists, tuples, and sets, and returns them sorted""" | |
# Prepare the ourput variable | |
output = [] | |
# Look for wheter an input is a list, tuple, or set | |
if isinstance(input, (list, tuple, set)): | |
# Lookp over that iterator, and extend the output by its flattened return | |
for item in input: | |
output.extend(flatten(item)) | |
else: | |
# Append a single NON-iterator item to the output | |
output.append(input) | |
return sorted(output) | |
if __name__ == '__main__': | |
print flatten(l) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment