Created
May 21, 2015 15:50
-
-
Save ma-ric/451ce328c4c84d18c8af to your computer and use it in GitHub Desktop.
Python; recursive flatten of nested iterables, with proper handling of string elements
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
#!/usr/bin/env python3 | |
def flatten(t): | |
""" | |
Generator flattening the structure | |
>>> list(flatten([2, [2, "test", (4, 5, [7], [2, [6, 2, 6, [6], 4]], 6)]])) | |
[2, 2, "test", 4, 5, 7, 2, 6, 2, 6, 6, 4, 6] | |
""" | |
from collections.abc import Iterable | |
for x in c: | |
if isinstance(x, str) or not isinstance(x, Iterable): | |
yield x | |
else: | |
yield from flatten(x) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment