3 Ways To Flatten Any List In Python

preview_player
Показать описание
Learn how you can flatten any list in Python. We will be exploring 3 different ways to do this. First will be through vanilla Python with the for loop, then we will use the faster list comprehension approach, and finally we will use the easiest approach with numpy.
Рекомендации по теме
Комментарии
Автор

One can also try this implementation:
def flatten_any(input_list: list) -> list:
return sum(map(flatten_any, input_list), []) if isinstance(input_list, list) else [input_list]

hydra
Автор

FYI - This was my interview question with Facebook. - Recursion would make anything flat whatever your throw at it.

jbn
Автор

Great! I was looking for this solution last week.

ezrawick
Автор

Just turn the array into a string, use list comp to filter

padraic
Автор

lst = [[[[1, 2], [3, 4, ['some', 'text']]], [[5, 6, [0, ['l', 'j']]], [7, 8]]], [9]]

print(lst)

# recursively flatten list using yield from to generate a new list
def flatten_list(lst):
for item in lst:
if isinstance(item, list):
yield from flatten_list(item)
else:
yield item





I would use this, much easier and flattens any number of nested lists with any content.

treadaar
Автор

I have a clean pythonic way to do this, but if the first index of the deepest item is list, set ou tuple, it ends the flatten function:

def flatten(input_list) -> list:

flatten_layer = [item for subitem in input_list for item in subitem]

if not isinstance(flatten_layer[0], (list, tuple, set)):
return flatten_layer

return flatten(flatten_layer)


if you copy this function you will see that it flattens any dimension of list given its other limits.

j.raimundosilva
Автор

So basically at first you just showed two functions to flatten them yourself and at the end you succumbed to using a superior implementation from numpy.Ok i guess.
I was expecting a recursive approach, but alright.

ZeroSleap