例如,我有这个:
list_of_lists = [
[[1,2,3], [4,5,6], [7,8,9] ],
[[11,22,33], [44,55,66], [77,88,99] ],
[[111,222,333], [444,555,666], [777,888,999]],
]
如何以最好的方式实现这一目标:
expected_result = [
[1,2,3,4,5,6,7,8,9],
[11,22,33,44,55,66,77,88,99],
[111,222,333,444,555,666,777,888,999]
]
答案 0 :(得分:3)
这对于一对嵌套列表推导并不太难:
result = [[x for inner in middle for x in inner] for middle in list_of_lists]
答案 1 :(得分:3)
最好的办法是将itertools.chain.from_iterable
与列表理解结合使用:
>>> from itertools import chain
>>> [list(chain.from_iterable(x)) for x in list_of_lists]
[[1, 2, 3, 4, 5, 6, 7, 8, 9], [11, 22, 33, 44, 55, 66, 77, 88, 99], [111, 222, 333, 444, 555, 666, 777, 888, 999]]
或者如果NumPy是一个选项:
In [47]: arr = np.array(list_of_lists)
In [48]: a, b, c = arr.shape
In [49]: arr.flatten().reshape(a, b*c)
Out[49]:
array([[ 1, 2, 3, 4, 5, 6, 7, 8, 9],
[ 11, 22, 33, 44, 55, 66, 77, 88, 99],
[111, 222, 333, 444, 555, 666, 777, 888, 999]])
答案 2 :(得分:1)
list_of_lists = [
[[1,2,3], [4,5,6], [7,8,9] ],
[[11,22,33], [44,55,66], [77,88,99] ],
[[111,222,333], [444,555,666], [777,888,999]],
]
import operator
expected_result = [reduce(operator.concat, List) for List in list_of_lists)]
答案 3 :(得分:0)
我会这样做
expected_result1 = list(map(lambda row: sum(row, []), list_of_lists))
print(expected_result)
print(expected_result1)
The output is:
#[[1, 2, 3, 4, 5, 6, 7, 8, 9], [11, 22, 33, 44, 55, 66, 77, 88, 99], [111, 222, 333, 444, 555, 666, 777, 888, 999]]
#[[1, 2, 3, 4, 5, 6, 7, 8, 9], [11, 22, 33, 44, 55, 66, 77, 88, 99], [111, 222, 333, 444, 555, 666, 777, 888, 999]]