比较两个列表时触发IndexError:列表索引超出范围求助
解决列表元素检查时的IndexError问题
错误原因
- 遍历逻辑错误:你写的
for i in firstList是直接遍历列表里的元素值,不是索引,但后续用firstList[i]把元素值当成索引去取数据,一旦元素值大于等于firstList的长度,必然触发索引越界错误。 - 拼写错误:代码里的
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
相关产品推荐
相关产品推荐

