Created
April 6, 2012 12:36
-
-
Save narma/2319350 to your computer and use it in GitHub Desktop.
python flatten
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
def make_flatten(fl_types=None): | |
if fl_types is None: | |
fl_types = (list, tuple) | |
def flatten(x): | |
for i in x: | |
if isinstance(i, fl_types): | |
for a in flatten(i): | |
yield a | |
else: | |
yield i | |
return flatten | |
flatten = make_flatten() | |
if __name__ == '__main__': | |
m = [[[1, 13], [2, 14], [3, 15]], | |
[[4, 16], [5, 17], [6]], | |
[[7], [8], [9]], | |
[[10], [11], [12]]] | |
assert list(flatten(m)) == [1, 13, 2, 14, 3, 15, 4, 16, 5, 17, 6, 7, 8, 9, 10, 11, 12] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment