2017-05-30 50 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

相关问题