Last active
September 1, 2015 05:19
-
-
Save trsqxyz/736b77c18ad064a1421f to your computer and use it in GitHub Desktop.
Python の yield from をつかって flatten する ref: http://qiita.com/trsqxyz/items/013ea4ece0de52328f17
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 flatten(x): | |
if hasattr(x, '__iter__') and not isinstance(x, str): | |
for y in x: | |
yield from flatten(y) | |
else: | |
yield x |
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
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