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

Python中IndexError: list index out of range问题解决求助

解决嵌套列表匹配时的IndexError问题

错误代码示例

listA = [
    ["192.168.1.1", "eth0", "255.255.255.0", "gateway", "active", "100", "up"],
    ["192.168.1.2", "eth1", "255.255.255.0", "server", "active", "99"],  # 缺少状态字段
    ["192.168.1.3", "eth2", "255.255.255.0", "client", "active", "98", "down"]
]
listB = ["192.168.1.2", "eth1", "255.255.255.0", "server", "active", "99"]

for sublist in listA:
    if sublist[:6] == listB[:6]:
        status = sublist[6]
        if status == "up":
            print("设备在线")
        else:
            print("设备离线")

错误输出

IndexError: list index out of range

问题原因

  • 子列表长度不足:listA中部分子列表只有6个元素,没有预留存储状态的第7个元素,代码尝试访问sublist[6]时触发索引越界。
  • 未做长度校验:遍历子列表时,没有先检查子列表是否包含足够元素就直接进行匹配和索引访问。

修复方案

给代码加上两层长度校验:先确保listB有至少6个元素,再确保listA中的子列表有至少7个元素,之后再执行匹配逻辑。

listA = [
    ["192.168.1.1", "eth0", "255.255.255.0", "gateway", "active", "100", "up"],
    ["192.168.1.2", "eth1", "255.255.255.0", "server", "active", "99"],
    ["192.168.1.3", "eth2", "255.255.255.0", "client", "active", "98", "down"]
]
listB = ["192.168.1.3", "eth2", "255.255.255.0", "client", "active", "98"]

# 校验listB长度,避免无效匹配
if len(listB) < 6:
    print("listB元素不足6个,无法执行匹配")
else:
    target_prefix = listB[:6]
    matched_status = None
    for sublist in listA:
        # 先检查子列表长度达标,再匹配前缀
        if len(sublist) >= 7 and sublist[:6] == target_prefix:
            matched_status = sublist[6]
            break
    
    # 根据匹配结果执行判断
    if matched_status == "up":
        print("设备在线")
    elif matched_status == "down":
        print("设备离线")
    else:
        print("未找到匹配的子列表或状态无效")

期望输出

当listB匹配第三个子列表时,输出:

设备离线

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 01:45:31