Skip to content

Instantly share code, notes, and snippets.

@trsqxyz
Last active September 1, 2015 05:19
Show Gist options
  • Save trsqxyz/736b77c18ad064a1421f to your computer and use it in GitHub Desktop.
Save trsqxyz/736b77c18ad064a1421f to your computer and use it in GitHub Desktop.
Python の yield from をつかって flatten する ref: http://qiita.com/trsqxyz/items/013ea4ece0de52328f17
def flatten(x):
if hasattr(x, '__iter__') and not isinstance(x, str):
for y in x:
yield from flatten(y)
else:
yield x
In : ls = [1,2,3,[4,5],[6,[7,8,[9,10,11],12]]]
In : list(flatten(ls))
Out: [1, 2, 3, 4, 5, 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