Skip to main content
 首页 » 编程设计

python之访问数组中的元素

2024年10月24日11TianFang

我如何访问这个数组或矩阵中的元素

array([[-0.0359075 ,  0.09684904, -0.03384908,  0.11583249, -0.06620416, 
         0.31124461,  0.2244373 , -0.22074385,  0.2731958 ,  0.35207385, 
        -0.0232635 ,  0.01991997, -0.14457113, -0.22119096, -0.23231329, 
        -0.25554115,  0.20723027,  0.21642838,  0.17261602, -0.14479494, 
        -0.02729147,  0.28598186, -0.14462787, -0.06030619,  0.10610376, 
         0.04492712, -0.03452296, -0.079672  , -0.13708481, -0.04986167, 
        -0.25361556, -0.03039704]], dtype=float32) 

如果这个矩阵是 r 那么当我 r[4] 访问我收到的第四个元素时

IndexError: index 1 is out of bounds for axis 0 with size 1  

当我尝试使用此命令访问时 r(4) 我收到了

TypeError: 'numpy.ndarray' object is not callable  

请您参考如下方法:

你有一个索引错误,因为你有向量但没有数组:

r = np.array([[-0.0359075 ,  0.09684904, -0.03384908,  0.11583249, -0.06620416, 
         0.31124461,  0.2244373 , -0.22074385,  0.2731958 ,  0.35207385, 
        -0.0232635 ,  0.01991997, -0.14457113, -0.22119096, -0.23231329, 
        -0.25554115,  0.20723027,  0.21642838,  0.17261602, -0.14479494, 
        -0.02729147,  0.28598186, -0.14462787, -0.06030619,  0.10610376, 
         0.04492712, -0.03452296, -0.079672  , -0.13708481, -0.04986167, 
        -0.25361556, -0.03039704]], dtype=np.float32) 
 
In [57]: r.shape 
Out[57]: (1, 32) 

要获得第 4 个元素,您需要为第二个轴调用 3,因为索引从 0 开始:

In [58]: r[0,3] 
Out[58]: 0.11583249   

或者您可以使用 reshape 从您的向量中创建数组:

In [65]: r.reshape(r.size, 1)[3] 
Out[65]: array([ 0.11583249], dtype=float32)  

注意:您可以从 docs 中找到很多关于索引的有用信息。