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

比较两个列表时触发IndexError:列表索引超出范围求助

解决列表元素检查时的IndexError问题

错误原因

  1. 遍历逻辑错误:你写的for i in firstList是直接遍历列表里的元素值,不是索引,但后续用firstList[i]把元素值当成索引去取数据,一旦元素值大于等于firstList的长度,必然触发索引越界错误。
  2. 拼写错误:代码里的secondlist和定义的secondList大小写不一致,后续会引发NameError(你当前先触发索引错误是因为还没走到这一步)。

修正后的代码

直接遍历firstList的元素,无需通过索引取值:

for item in firstList:
    if item in secondList:
        print(f"{item} at index {secondList.index(item)}")
    else:
        print(f"{item} not found in list")

补充说明

如果secondList里存在重复元素,index()方法只会返回第一个匹配元素的索引。如果需要获取该元素在secondList中的所有索引,可以用下面的写法:

for item in firstList:
    indices = [idx for idx, val in enumerate(secondList) if val == item]
    if indices:
        for idx in indices:
            print(f"{item} at index {idx}")
    else:
        print(f"{item} not found in list")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 13:31:03