Skip to content

Instantly share code, notes, and snippets.

@narma
Created April 6, 2012 12:36
Show Gist options
  • Save narma/2319350 to your computer and use it in GitHub Desktop.
Save narma/2319350 to your computer and use it in GitHub Desktop.
python flatten
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