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

for循环内if语句新增条件后触发索引越界的原因及规避方法

解决列表遍历中访问下一个元素的索引越界问题

你的问题根源很明确:当循环执行到列表的最后一个元素时,idx+1会超出列表的最大索引范围,导致IndexError。以下是几种可行的解决方式:

方法1:限制循环范围到倒数第二个元素

通过切片arr[:-1]去掉列表的最后一个元素,这样循环只会遍历到倒数第二个元素,idx+1始终是有效的索引:

arr = ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]
liste = []
for idx, i in enumerate(arr[:-1]):
    if (i == 'NORTH' and arr[idx+1] == 'SOUTH') or \
       (i == 'SOUTH' and arr[idx+1] == 'NORTH') or \
       (i == 'EAST' and arr[idx+1] == 'WEST') or \
       (i == 'WEST' and arr[idx+1] == 'EAST'):
        liste.append(idx)
        liste.append(idx+1)
print(liste)  # 输出: [0, 1, 3, 4]

方法2:循环内添加索引合法性判断

在执行条件判断前,先检查当前索引是否不是最后一个,确保idx+1存在:

arr = ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]
liste = []
for idx, i in enumerate(arr):
    # 先确认还有下一个元素
    if idx < len(arr) - 1:
        if (i == 'NORTH' and arr[idx+1] == 'SOUTH') or \
           (i == 'SOUTH' and arr[idx+1] == 'NORTH') or \
           (i == 'EAST' and arr[idx+1] == 'WEST') or \
           (i == 'WEST' and arr[idx+1] == 'EAST'):
            liste.append(idx)
            liste.append(idx+1)
print(liste)  # 输出: [0, 1, 3, 4]

方法3:用字典简化反向判断逻辑

可以用字典存储方向的反向映射,让代码更简洁易维护,同时结合方法1的循环范围限制:

arr = ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]
liste = []
# 定义方向的反向映射
opposite_directions = {
    'NORTH': 'SOUTH',
    'SOUTH': 'NORTH',
    'EAST': 'WEST',
    'WEST': 'EAST'
}

for idx, current_dir in enumerate(arr[:-1]):
    if arr[idx+1] == opposite_directions[current_dir]:
        liste.append(idx)
        liste.append(idx+1)
print(liste)  # 输出: [0, 1, 3, 4]

以上三种方法都能解决索引越界问题,同时适配随机生成的方向列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 20:25:23