1
0

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.

初期化済みの配列を用意する

Posted at

初期化済みの配列

Pythonで初期化済みの配列がほしいことがあります
例えばこんなの

ARRAYNUM = 3
array = [0, 0, 0]

しかしこれでは、ARRAYNUMが生きてません
そこでこんな書式が便利です

array = [0] * ARRAYNUM

もちろん、Noneや空文字での初期化も出来ます

arraynone = [None] * ARRAYNUM
arraystr = [''] * ARRAYNUM

配列の配列

もちろん配列の配列もやっちゃいましょう

#間違ったコード
arrayarray = [[]] * ARRAYNUM

これは以下のコードと等価です

a = []
arrayarray = [a, a, a]


# 同じインスタンスなのでどこか一箇所を変更すると全部変わる
arrayarray[0].append(0)
# aの中身は[[0], [0], [0]]

同じインスタンスをコピーしてしまうので、全部同じものになるんですね
もちろん、クラスなんかも同様なので、上記の書き方は問題になります
なので以下の書き方で対応しましょう

#正しいコード
[ [] for _i in range(ARRAYNUM) ]
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?