Created
April 8, 2018 10:11
-
-
Save BoeingX/f5283bd817a4f9ab71c7f76957fdc274 to your computer and use it in GitHub Desktop.
Recursively flatten a nested iterable
This file contains hidden or 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
| #!/usr/bin/env python | |
| # -*- coding: utf-8 -*- | |
| import collections | |
| def flatten(lst): | |
| """Flatten a iterable. | |
| >>> from __future__ import print_function | |
| >>> lst = [[1, 2], [], [1, [[2, 3], 3]], 4, 5] | |
| >>> print(flatten(lst)) | |
| [1, 2, 1, 2, 3, 3, 4, 5] | |
| """ | |
| assert(isinstance(lst, collections.Iterable)) | |
| if not len(lst): | |
| return lst | |
| head, *tail = lst | |
| if isinstance(head, collections.Iterable): | |
| return flatten(head) + flatten(tail) | |
| return [head] + flatten(tail) | |
| if __name__ == '__main__': | |
| import doctest | |
| doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment