首页 > 解决方案 > 对于选定数字的循环迭代(不使用范围)

问题描述

这是一个示例代码,但基本上我试图只选择一定范围的数字,比如 2、4 和 6,并将 3D 随机值数组的第一个轴乘以前 2,然后乘以 4 和 6,然后存储新数组(其大小仍应为 3、30 和 10)。我一直收到这个错误。我正在做的事情很简单,但我对我的 for 循环有什么问题感到困惑?我最初尝试过 np.array([2,4,6]) 但我仍然遇到同样的错误。

data = np.random.rand(3,30,10)

data_new = np.zeros((data.shape))

for i in [2,4,6]:
    data_new[i,:,:] = data[i]*i

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
/tmp/ipykernel_202420/2883607738.py in <module>
      4 
      5 for i in [2,4,6]:
----> 6     data_new[i,:,:] = data[i]*i
      7 

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

标签: pythonnumpyjupyter

解决方案


我想你的意思是:

for i in [2,4,6]:
    data_new[:, :, i] = data[:, :, i]*i

推荐阅读