Python中使用if语句时出现List index out of range错误
列表遍历索引越界错误分析与解决
问题场景
给定列表:
text_split = [['5', '5', '12\n'], ['1', '1\n'], ['1', '2\n'], ['2', '1\n'], ['2', '3\n'], ['3', '1\n'], ['3', '2\n'], ['3', '4\n'], ['4', '2\n'], ['4', '4\n'], ['1', '2\n'], ['2', '3\n'], ['5', '5']]
使用以下循环遍历列表,判断子列表第一个元素是否为'1':
for i in range(1, len(text_split)+1, 1): if text_split[i][0] == '1': print("True")
执行后会在对应位置输出True,但最终抛出IndexError: list index out of range错误,无法完成遍历;而单独执行print(text_split[6][0])可以正常输出3。
错误原因
- Python列表的索引从0开始,
text_split的长度是13,有效索引范围是0到12(包含两端)。 - 循环中
range(1, len(text_split)+1)会生成1到13的整数序列,当i=13时,text_split[13]超出了列表的最大有效索引,直接触发索引越界错误。 - 单独访问
text_split[6]没问题,是因为6属于0-12的有效索引区间。
解决方案
方案1:修正索引遍历范围
将循环的索引范围改为从0开始,到列表长度结束(range(len(text_split))会生成0到12的序列):
for i in range(len(text_split)): if text_split[i][0] == '1': print("True")
方案2:直接遍历列表元素(更简洁)
不需要通过索引访问,直接遍历列表中的每个子列表:
for sub_list in text_split: if sub_list[0] == '1': print("True")
内容的提问来源于stack exchange,提问作者Daniielle
相关产品推荐
相关产品推荐

