2017-05-30 51 views
-1
import numpy as np 

weights = np.random.standard_normal((2,2,3)) 
b = weights 
c = weights 
c[0,1,:] = c[0,1,:] + [1,1,1] 

print b[0,1] 
print ('##################') 
print c[0,1] 
print ('##################') 
print (np.sum(b-c)) 

結果是爲什麼我不能在numpy中更改3d數組的元素?

[ 1.76759245 0.87506255 2.83713469] 
################## 
[ 1.76759245 0.87506255 2.83713469] 
################## 
0.0 

Process finished with exit code 0 

你可以看到,元素並沒有改變。 爲什麼?

在此先感謝

+0

因爲'b'和'c'都是數組'weights'中相同位置的視圖。 – Divakar

+0

元素已更改。 'b'和'c'是同一個數組。 – user2357112

回答

0

其實,他們確實改變了。問題在於你引用的是同一個對象,只能在更改後查看它。如果您在b上使用copy(),則會在更改前看到這些值。 bc是當前代碼中的相同對象; Is Python call-by-value or call-by-reference? Neither.在更廣泛的意義上是一個體面的閱讀。

import numpy as np 

weights = np.random.standard_normal((2,2,3)) 
b = weights.copy() # Create a new object 
c = weights 
c[0,1,:] = c[0,1,:] + [1,1,1] 

print b[0,1] 
print ('##################') 
print c[0,1] 
print ('##################') 
print (np.sum(b-c)) 
+0

謝謝,我明白了 – wyp

相關問題