Сгладить список в Python означает преобразовать вложенный список в одномерный список. Вот несколько способов добиться этого:
Метод 1: использование цикла и рекурсии
def flatten_list(lst):
flattened_list = []
for item in lst:
if isinstance(item, list):
flattened_list.extend(flatten_list(item))
else:
flattened_list.append(item)
return flattened_list
# Example usage
nested_list = [1, [2, [3, 4], 5], 6]
flattened = flatten_list(nested_list)
print(flattened)
Метод 2: использование понимания списка и рекурсии
def flatten_list(lst):
return [item for sublist in lst for item in (flatten_list(sublist) if isinstance(sublist, list) else [sublist])]
# Example usage
nested_list = [1, [2, [3, 4], 5], 6]
flattened = flatten_list(nested_list)
print(flattened)
Метод 3. Использование модуля itertools
import itertools
nested_list = [1, [2, [3, 4], 5], 6]
flattened = list(itertools.chain.from_iterable(nested_list))
print(flattened)
Метод 4. Использование функции reduceиз модуля functools
from functools import reduce
nested_list = [1, [2, [3, 4], 5], 6]
flattened = list(reduce(lambda x, y: x + y if isinstance(x, list) else [x] + y, nested_list))
print(flattened)