LoginSignup
4
1

More than 5 years have passed since last update.

python3で2重配列をflattenする

Posted at

例えばこんなリストがあるとする。

a = [[1], [1, 2, 3], [1, 2], [1, 2, 3]]

こいつをflattenしてこんな感じにしたいとする。

b = [1, 1, 2, 3, 1, 2, 1, 2, 3]

 方法1

reduceを使う。

from functools import reduce
a = [[1], [1, 2, 3], [1, 2], [1, 2, 3]]
b = reduce(lambda x, y: x+y, a)
print(b)
#[1, 1, 2, 3, 1, 2, 1, 2, 3]

 方法2

chainを使う。

from itertools import chain
a = [[1], [1, 2, 3], [1, 2], [1, 2, 3]]
b = list(chain.from_iterable(a))
print(b)
#[1, 1, 2, 3, 1, 2, 1, 2, 3]
# chainオブジェクトに最後にlistを噛ませてやる必要がある

あとはnumpyのflatten()を使うとか。

4
1
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
4
1