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

Python中使用大于运算符比较列表元素时触发IndexError: list index out of range

筛选列表中大于下一个元素的元素(解决索引越界问题)

问题描述

需要实现一个功能:遍历列表,将当前元素大于下一个元素的项加入新列表。原代码运行时出现IndexError: list index out of range错误,尝试enumerate函数后仍存在相同问题。

原代码:

def solution(A):
    row1 = []
    for index in range(len(A)):
        if A[index] > A[index + 1]:
            row1.append(A[index])

    return row1


print(solution(A=[5, 4, 3, 6, 1]))

报错信息:

Traceback (most recent call last):
  File "/home/zeddy/PycharmProjects/pythonProject1/index.py", line 11, in <module>
    print(solution(A=[5, 4, 3, 6, 1]))
  File "/home/zeddy/PycharmProjects/pythonProject1/index.py", line 5, in solution
    if A[index] > A[index + 1]:
IndexError: list index out of range

Process finished with exit code 1

错误原因

原循环range(len(A))会遍历列表的所有索引(比如长度为5的列表,索引是0-4)。当循环到最后一个索引(4)时,A[index+1]即A[5],超出了列表的最大索引(4),导致索引越界错误。

修正方案

方案1:限制循环范围

直接将循环范围改为range(len(A)-1),只遍历到倒数第二个元素,这样index+1始终是合法索引:

def solution(A):
    row1 = []
    # 遍历到倒数第二个元素,避免index+1越界
    for index in range(len(A) - 1):
        if A[index] > A[index + 1]:
            row1.append(A[index])
    return row1

print(solution(A=[5, 4, 3, 6, 1]))  # 输出: [5, 4, 6]

方案2:用enumerate判断索引位置

使用enumerate遍历元素和索引时,增加判断条件,确保当前不是最后一个元素:

def solution(A):
    row1 = []
    for index, num in enumerate(A):
        # 仅处理存在下一个元素的项
        if index < len(A) - 1 and num > A[index + 1]:
            row1.append(num)
    return row1

print(solution(A=[5, 4, 3, 6, 1]))  # 输出: [5, 4, 6]

方案3:用zip配对相邻元素(简洁写法)

利用zip(A, A[1:])将当前元素和下一个元素配对,再通过列表推导式筛选符合条件的元素:

def solution(A):
    # zip(A, A[1:]) 会生成(5,4),(4,3),(3,6),(6,1)这样的元组对
    return [current for current, next_num in zip(A, A[1:]) if current > next_num]

print(solution(A=[5, 4, 3, 6, 1]))  # 输出: [5, 4, 6]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 22:01:28