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

遍历列表比较元素时触发Index Error的问题求助

解决列表相邻元素比较时的IndexError问题

你的代码触发IndexError的核心原因是:当循环到列表最后一个元素时,index + 1会超出列表的索引范围。比如sorted_number长度为6,最大有效索引是5,当index等于5时,sorted_number[6]不存在,直接抛出索引越界错误。

下面是几种修复方案:

方案1:限制循环索引范围

只遍历到倒数第二个元素,从根源避免index + 1越界:

numbers = [1,2,3,4,5,6]
sorted_number = sorted(numbers)

for index in range(len(sorted_number) - 1):
    current = sorted_number[index]
    next_num = sorted_number[index + 1]
    if next_num % current == 1:
        print(index, current)

方案2:循环内判断跳过最后一个元素

在循环中添加条件,遇到最后一个元素时直接终止:

numbers = [1,2,3,4,5,6]
sorted_number = sorted(numbers)

for index, num in enumerate(sorted_number):
    if index == len(sorted_number) - 1:
        break
    if sorted_number[index + 1] % num == 1:
        print(index, num)

方案3:用zip配对相邻元素(更Pythonic)

利用zip将当前元素和下一个元素自动配对,无需手动处理索引:

numbers = [1,2,3,4,5,6]
sorted_number = sorted(numbers)

for index, (current, next_num) in enumerate(zip(sorted_number, sorted_number[1:])):
    if next_num % current == 1:
        print(index, current)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 08:40:26