删除Numpy数组首尾元素时触发IndexError的问题求助
解决numpy数组处理时的IndexError问题
你的错误根源很明确:当数组里的元素被全部配对移除后,数组变成空的(size=0),这时候再去访问dice[0]或者dice[-1]自然会触发索引越界错误。
修复思路
在每次尝试计算首尾元素之和前,先检查数组是否还有足够元素(至少2个)。如果数组元素不足2个,直接终止循环,避免无效的索引访问。
修改后的代码
import numpy as np no_of_dice = 10 dice = np.random.randint(1, high=11, size=no_of_dice) print(dice) # 移除所有10 no_of_tens = np.count_nonzero(dice == 10) print("Number of 10s:", no_of_tens) dice = np.delete(dice, np.where(dice == 10)) dice = np.sort(dice) print(dice.shape, dice) no_of_pairs = 0 # 循环条件加入数组长度判断,确保至少有2个元素才执行配对逻辑 while len(dice) >= 2 and (dice[0] + dice[-1] >= 10): # 一次性删除首尾元素,简化操作 dice = np.delete(dice, [-1, 0]) no_of_pairs += 1 print(dice) print("Number of pairs:", no_of_pairs)
关键改动说明
- 循环条件优化:把原有的
while sum >= 10改成while len(dice) >= 2 and (dice[0] + dice[-1] >= 10),从根源上避免了空数组或单元素数组的索引访问错误。 - 合并删除操作:将两次单独的
np.delete调用合并成一次,通过[-1, 0]参数同时删除首尾元素,代码更简洁高效。 - 移除冗余变量:直接在循环条件内计算首尾元素和,不需要提前初始化
sum变量,避免了数组为空时的提前报错。
这样修改后,无论数组最后被删到空还是剩下单个元素,都不会再触发索引越界错误了。
内容的提问来源于stack exchange,提问作者enea19
相关产品推荐
相关产品推荐

