#python #python_3x #списки
Имеется: [[1], [2], [3]] нужно: [1, 2, 3]
Ответы
Ответ 1
>>> a = [[1], [2], [3]] >>> sum(a, []) [1, 2, 3] >>> a = [[1, 2], [3, 4], [5, 6]] >>> sum(a, []) [1, 2, 3, 4, 5, 6]Ответ 2
>>> a = [[1], [2], [3]] >>> [x for l in a for x in l] [1, 2, 3]Ответ 3
Ну или вот так: from itertools import chain list(chain.from_iterable(a))Ответ 4
a = [[1], [2], [3]] print([i[0] for i in a])Ответ 5
result = [] for x in [[1], [2], [3]]: result.append(x.pop()) или [x.pop() for x in [[1], [2], [3]]]Ответ 6
Вариант через from functools import reduce: from functools import reduce from operator import add items = [[1], [2], [3]] print(reduce(add, items)) # [1, 2, 3] # Через лябмду print(reduce(lambda a, b: a + b, items)) # [1, 2, 3]Ответ 7
еще вариант outer = [[1,2,3], [4,5,6], [7,8,9]] new_list = [item for sublist in outer for item in sublist] получим [1,2,3,4,5,6,7,8,9]
Комментариев нет:
Отправить комментарий