Created
May 28, 2024 12:48
-
-
Save zshn25/5869e16b8fe436213414208d445a58cb to your computer and use it in GitHub Desktop.
Python utils
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 typing import Iterable | |
#from collections import Iterable # < py38 | |
def flatten(items): | |
"""Yield items from any nested iterable; | |
Source: https://stackoverflow.com/a/40857703 | |
Usage: | |
complicated = [[1, [2]], (3, 4, {5, 6}, 7), 8, "9"] # numbers, strs, nested & mixed | |
list(flatten(complicated)) | |
# [1, 2, 3, 4, 5, 6, 7, 8, '9'] | |
""" | |
for x in items: | |
if isinstance(x, Iterable) and not isinstance(x, (str, bytes)): | |
for sub_x in flatten(x): | |
yield sub_x | |
else: | |
yield x |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment