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

使用enumerate遍历数组对比相邻元素时如何避免索引越界错误

问题原因

你遇到的index out of range error是因为遍历到数组最后一个元素时,index + 1超出了数组的最大合法索引(数组最大索引为len(array) - 1)。

基于enumerate的修复方案

不需要修改enumerate本身的用法,只要调整你遍历的数组切片即可:只遍历数组除最后一位外的所有元素,就能保证index + 1永远合法,同时enumerate返回的索引和原数组完全对应,不影响后续用索引执行操作。
修复后的示例代码如下:

array = [1,2,3,4]

# 遍历除最后一个元素外的所有元素,index最大为 len(array)-2,index+1不会越界
for index,i in enumerate(array[:-1]): 
    if array[index] > array[index+1]: 
        # 此处执行你需要的索引相关操作即可
        pass

如果你不想切数组,也可以在循环内加终止判断,写法如下:

array = [1,2,3,4]

for index,i in enumerate(array): 
    # 遍历到最后一个元素时直接终止循环
    if index == len(array) - 1:
        break
    if array[index] > array[index+1]: 
        # 执行对应操作
        pass

两种写法都完全基于enumerate实现,不需要改用其他循环方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 02:45:00