Created
October 28, 2020 14:56
-
-
Save Cellebyte/95e761ae208dfcabcd743995afe096a3 to your computer and use it in GitHub Desktop.
Flatten a list with comprehensions and a generator.
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 Generator, Any | |
def list_flatten(l: list) -> Generator[Any,None,None]: | |
for item in l: | |
if isinstance(item, list): | |
yield from list_flatten(item) | |
else: | |
yield item | |
if __name__ == '__main__': | |
data = [["a"],["b",["c",["d"]]]] | |
flat_list = [item for item in list_flatten(data) if item] | |
print(flat_list) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment