You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python使用enumerate遍历数组触发IndexError报错求助

Python运行报错排查:IndexError: too many indices for array

问题复现

现有命名为tot的数组,打印内容如下:

[112 100  22  90  12  48 115  85  13  40  99  93 100  27  21  14  23 100]

编写用于生成随机解的函数代码如下:

def randomSolution():
    somma = 0;
    for i in enumerate(tot): 
        if somma<=3600: 
            countS[i] = 1
            somma = somma + tot[i]
        else: 
            break
    return countS
rand_sol = randomSolution()
print(rand_sol)

在Jupyter Lab环境运行上述代码时抛出错误:

Index Error: too many indices for array.

报错根因

  • 直接触发报错的问题:enumerate()遍历序列时,返回的每一项是**(索引, 元素值)** 格式的二元元组,代码中直接将整个元组赋值给变量i,后续用i作为下标访问一维数组countS、tot时,相当于传入了不符合一维数组索引规则的元组参数,直接触发索引错误。
  • 隐藏逻辑问题1:代码未提前定义、初始化countS数组,即使修复索引问题,也会触发变量未定义的报错。
  • 隐藏逻辑问题2:现有代码从数组头部开始顺序累加元素,没有任何随机选择逻辑,和“生成随机解”的功能预期不符。
  • 隐藏逻辑问题3:tot数组所有元素求和仅为1114,远小于判断阈值3600,现有逻辑下循环永远不会触发break,会遍历完整个数组将所有位置标记为1。

修复方案

最小可用修复(解决当前报错)

修复索引用法,提前初始化countS数组,代码可直接运行:

import numpy as np
# 定义tot数组(原打印内容为numpy数组输出格式,补全逗号分隔)
tot = np.array([112, 100, 22, 90, 12, 48, 115, 85, 13, 40, 99, 93, 100, 27, 21, 14, 23, 100])
# 提前初始化和tot等长的countS数组,初始值全为0
countS = np.zeros(len(tot), dtype=int)

def randomSolution():
    somma = 0
    # 拆包enumerate返回的元组,idx接收索引,val接收当前元素值
    for idx, val in enumerate(tot): 
        if somma <= 3600: 
            countS[idx] = 1
            somma = somma + val
        else: 
            break
    return countS

rand_sol = randomSolution()
print(rand_sol)

符合随机解需求的优化版本

新增随机打乱逻辑,实现随机选择元素、选中元素总和不超过3600的效果:

import numpy as np

tot = np.array([112, 100, 22, 90, 12, 48, 115, 85, 13, 40, 99, 93, 100, 27, 21, 14, 23, 100])
countS = np.zeros(len(tot), dtype=int)

def randomSolution():
    somma = 0
    # 每次调用重置countS为全0
    countS[:] = 0
    # 生成打乱的索引序列,实现随机选择效果
    shuffled_indices = np.random.permutation(len(tot))
    for idx in shuffled_indices:
        current_val = tot[idx]
        # 加当前值不超阈值才标记选中
        if somma + current_val <= 3600:
            countS[idx] = 1
            somma += current_val
    return countS, somma

rand_sol, selected_total = randomSolution()
print("随机解标记数组:", rand_sol)
print("选中元素总和:", selected_total)

内容的提问来源于stack exchange,提问作者Alba

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 17:42:23