LoginSignup
0
0

More than 3 years have passed since last update.

【Python3】多次元のリストを一次元にする

Last updated at Posted at 2019-06-20

はじめに

numpyつかえよって話かもしれませんが、スクレイピングとかデータを取得・加工するときは多次元リストを一次元にしたいとおもうことがよくあったので、関数を載せときます.

-- 追記 --

shiracamusさんにコメントいただいたので追記します

下の記事などとても参考になります
Python 3 で flatten する方法いろいろ

多次元のリスト

こんなかんじのやつ

# 例として,なにも規則性のない多次元リスト
l = [[0, 1, 2],[10, 11, [12], 13], [4]]

output

def list_dim(l):
    """
    リストの次元数を算出
    """
    dimention = 1 if isinstance(l, list) else 0
    return dimention + max([list_dim(l_) for l_ in l]) if isinstance(l, list) else dimention

def multidim2onedim(l):
    """
    多次元のリストを1次元に修正
    """
    if list_dim(l) > 1:
        onedim_list = []
        [onedim_list.extend(l_) if isinstance(l_, list)
         else onedim_list.append(l_) for l_ in l]
        return multidim2onedim(onedim_list)
    else:
        # 次元数が1になったら終了
        return l

usage

l = [[0, 1, 2],[10, 11, [12], 13], [4]]
multidim2onedim(l) # '[0, 1, 2, 10, 11, 12, 13, 4]'

参考

再帰関数を理解するための最もシンプルな例

0
0
2

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