やりたいこと
以下のような変換を行う。
変換前
[
[[1, 2], [3, 4], [5, 6]],
[[7, 8], [9, 10]],
[[11, 12]],
]
変換後
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]]
リスト内包表記
flattened_list = [item for sublist in nested_list for item in sublist]
itertools.chain.from_iterable() を利用
from itertools import chain
flattened_list = list(chain.from_iterable(nested_list))
sum() でリストを連結(リストの加算)
flattened_list = sum(nested_list, [])
リストの加算で ['a', 'b'] + ['c'] が ['a', 'b', 'c'] になることをイメージするとわかりやすい。
ループして extend() で連結
flattend_list = []
for sublist in nested_list:
flattend_list.extend(sublist)