0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python で入れ子のリストを平坦化

Posted at

やりたいこと

以下のような変換を行う。

変換前
[
    [[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)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?