LoginSignup
0
1

More than 3 years have passed since last update.

[python] 二次元リストの平坦化

Last updated at Posted at 2021-04-16

二次元リストなどイテレータの二重構造になっているものの平坦イテレータを取得するには、itertoolsのchain.from_iterableを使う。

import itertools

l_2d = [[0, 1], [2, 3]]

print(list(itertools.chain.from_iterable(l_2d)))
# [0, 1, 2, 3]

ちなみに、itertools.chain()は、イテレータの結合につかうもの。

from itertools import  chain
import numpy as np

nums = np.array([[0, 1, 2], [10, 11, 12], [20, 21, 22]])
zeros = np.zeros((2, 3))
print(list(chain(nums, zeros)))
# [array([0, 1, 2]), array([10, 11, 12]), array([20, 21, 22]), array([0., 0., 0.]), array([0., 0., 0.])]
0
1
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
1