29
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Python】二次元リストを一次元リストに変換する方法

Last updated at Posted at 2020-04-30

Pythonで二次元リストを一次元リストに変換したい場合がある。
sum関数を使えば一行で変換可能。

知らないと一見何をしている処理なのか分からないけど、使ってみると意外と便利。
三次元リストを一次元リストに変換したい場合はsum関数を二回使えばよい。

x = [[1, 2], [3, 4]]
x = sum(x, [])
print(x) # [1, 2, 3, 4]

y = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
y = sum(sum(y, []), [])
print(y) # [1, 2, 3, 4, 5, 6, 7, 8]

速度重視の場合はitertools.chain.from_iterable()を使う。
こちらの方がsum関数を使う場合よりも高速。

import itertools
x = [[1, 2], [3, 4]]
x = itertools.chain.from_iterable(x)
print(list(x)) # [1, 2, 3, 4]

y = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
y = itertools.chain.from_iterable(list(itertools.chain.from_iterable(y)))
print(list(y)) # [1, 2, 3, 4, 5, 6, 7, 8]

上記の他にも自作関数を作るという方法もある。
リストの次元数に依らないので、様々な次元数のデータを扱うときはオススメ。

29
20
1

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
29
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?