LoginSignup
1
7

More than 5 years have passed since last update.

pythonで多次元配列を作成する関数を自作した

Posted at

初めに

pythonの多次元配列を作るには内包表記を入れ子にしなければなりません。
それでは面倒なので多次元配列を作る関数を自作しました。

ソースコード


def make_array(n,init_elem=0,td=1):
       dimension=len(n)
       if td>=dimension:
           return [init_elem for i in range(n[td-1])]
       else:
           return [make_array(n,init_elem,td+1) for i in range(n[td-1])]

すごくシンプルですね。
再帰関数を使っているだけです。

使い方

1次元配列を定義する

print(make_array([10],0))
#[0,0,0,0,0,0,0,0,0,0]

初期化する数値を変える

print(make_array([10],1))
#[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

5*4の2次元配列

print(make_array([5,4],0))
#[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

5次元配列(2*2*2*2*2)

print(make_array([2]*5,0))
#[[[[[0, 0], [0, 0]], [[0, 0], [0, 0]]], [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]], [[[[0, 0], [0, 0]], [[0, 0], [0, 0]]], [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]]]

まとめ

pythonはシンプルにソースコードが書けますね。

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