計算過程の保持
code:p01.py
hist = []
x = 1
for i in range(10):
hist.append(x)
x = x + 1
print(hist)
# 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
これはOK
では、対象となる変数を配列にし、値の更新を添字を用いた要素指定とする。
code:p02.py
import numpy as np
hist1 = []
x = np.array(1) # (A)
for i in range(5):
hist1.append(x) # (B)
x0 = x0 + 1 # (C)
hist1.append(x)
hist2 = np.stack(hist1)
print(hist2) # (D)
code:結果.txt
[5
5
5
5
5
5]
全て同じ値となった。
(C)の代入は(A)で生成したインスタンス「x」に対して行われているため、計算結果を保持する新たなインスタンスは生成されていない。
(B), (B')でhist1に追加されているのは、(A)で生成したインスタンス「x」への参照である。
したがって、(D)で表示した時点におけるインスタンス「x」の値が出力されている。
確認しよう
code:p03.py
import numpy as np
hist1 = []
x = np.array(0)
for i in range(5):
hist1.append(x)
x0 = x0 + 1
hist1.append(x)
for i in hist1:
print(id(i))
code:結果.txt
140118823744400
140118823744400
140118823744400
140118823744400
140118823744400
140118823744400
hist1が保持する要素は全て同じインスタンスへの参照であるため、最後に更新された「x[0]」の値が出力される。
解決策
flatten() は ndarray 型のデータを1次元に変換し、新たなインスタンスを生成する。
code:p04.py