Python运行numpy代码触发IndexError索引越界错误怎么解决?
错误原因分析
- 你调用
reallyrandom(1,2,9)时,传入的第一个参数对应函数内的int1=1,np.random.randint(0,10, size=int1)会生成长度为1的一维numpy数组x,x乘以int2得到的y数组长度同样为1。 - numpy数组的索引从0开始计数,长度为1的数组合法索引只有
0,你传入的第三个参数对应int3=9,代码尝试访问y[9]显然超出了数组的边界,和报错提示index 9 is out of bounds for axis 0 with size 1完全对应。
修复方案
方案1:调整传参逻辑
保证要访问的索引值小于数组长度即可,比如把调用代码修改为:
# 数组长度为10,合法索引范围0~9,访问索引9符合要求 reallyrandom(10,2,9)
方案2:给代码添加合法性校验,避免直接崩溃
如果想要提升代码鲁棒性,可在访问索引前增加判断逻辑,修改后的函数如下:
import numpy as np import random def reallyrandom(arg1, arg2, arg3): int1=int(arg1) int2=int(arg2) int3=int(arg3) # 先校验索引是否合法 if int3 < 0 or int3 >= int1: print(f"参数非法:要访问的索引为{int3},但数组长度仅为{int1},合法索引范围是0~{int1-1}") return np.random.seed(42) x=np.random.randint(0,10, size=int1) print(x) print(x.shape) y=x*int2 print(y) print(y.shape) z=y[int3] print(z) print(f"Your random value is {z}") # 测试非法参数也不会直接报错 reallyrandom(1,2,9)
内容的提问来源于stack exchange,提问作者ejak7
相关产品推荐
相关产品推荐

