Last active
June 21, 2024 02:29
-
-
Save GaryLee/713f2c8a8ce260498ff0f496d32062b8 to your computer and use it in GitHub Desktop.
Flatten nested Python sequence object.
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
from collections.abc import Sequence | |
def flatten(x): | |
"""Flatten given parameter recursively.""" | |
if isinstance(x, Sequence): | |
for v in x: | |
yield from flatten(v) | |
else: | |
yield x | |
if __name__ == '__main__': | |
data = [1,2,[[3,4],5,[2,[3,4,5]]],[6,7],100,] | |
print(list(flatten(data))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment