请问Python报错IndexError: list index out of range该如何处理

初学Python,在写一个文本数据处理的脚本时出现以下问题,在程序中函数Option里的optionB.append(option[i][1])在运行时报错为IndexError: list index out of range,以下是源码部分,希望各位赐教,由于排版问题希望处理的数据无法上传,我只能以截图向各位展示,请见谅。

import re
fopen = open("c:\\test.txt",'r')
lines = fopen.readlines()
count =len(lines)  #题目总数
result = []      #抽取出的原始数据分行
topic = []       #题目
type = []        #题目类型
str = []         #原始数据以",作为分割符,相当于分列
optionA = []     #选项A
optionB = []
optionC = []
optionD = []
optionE = []
option = []      #选项整体
answer = []      #答案

def Result():
    for line in lines:
        str.append(line)
    for i in range(count):
        result.append((str[i].split("\",")))

"""for line in lines:
    result.append(line)
for i in range(count):
    str.append(result[i].split("\","))"""

def DefType():                    #对题目类型进行判断,并以字段type记录
    deftype = []
    for i in range(count):
        deftype.append(result[i][2])
        if re.findall('\d',deftype[i]) == ['1']:
            type.append("单选题")
        elif re.findall('\d',deftype[i]) == ['2']:
            type.append("多选题")
        elif re.findall('\d',deftype[i]) == ['4']:
            type.append("判断题")
def Topic():                      #题目
    deftopic = []
    for i in range(count):
        deftopic.append(result[i][4])
        index = deftopic[i].find("\"")+1
        topic.append(deftopic[i][index:].strip("\""))
def Option():                     #选项
    defoption = list()
    for i in range(count):
        defoption.append(result[i][8])
    for i in range(count):
        option.append(defoption[i].split("$;$"))
        index = option[i][0].find("\"") + 1
        optionA.append(option[i][0][index:])
        #optionB.append(option[i][1])
def Answer():                     #答案
    defanswer = []
    for i in range(count):
        defanswer.append(result[i][9])
        index = defanswer[i].find("\"") + 1
        answer.append(defanswer[i][index:].strip("\""))
"""def Test():         #测试用,无意义
    for i in range(count):
        if len(option[i][1])>0:
            optionB.append(option[i][1])"""
Result()
DefType()
Topic()
Option()
Answer()
#Test()

Jason990420
最佳答案

The length of string.split(sep) will be only 1 if sep not found in string, there’s only item option[i][0], no item option[i][1], that’s why you got exception IndexError: list index out of range.

It is something like this

def Option():
    defoption = list()
    for i in range(count):
        defoption.append(result[i])
    for i in range(count):
        option.append(defoption[i].split("$;$"))
        index = option[i][0].find("\"") + 1
        optionA.append(option[i][0][index:])
        if "$;$" not in defoption[i]:
            print(f'Exception for "$;$" not in {repr(defoption[i])}')
            print(f'option[{i}] is {option[i]} with length {len(option[i])}')
        optionB.append(option[i][1])

option  = []
optionA = []
optionB = []
result  = ['123$;$456', '123$;$456', '123:::456', '123$;$456']
count = len(result)
Option()
Exception for "$;$" not in '123:::456'
option[2] is ['123:::456'] with length 1
Traceback (most recent call last):
  File "<module2>", line 19, in <module>
  File "<module2>", line 12, in Option
IndexError: list index out of range

Note:

  • Not to use Python keyword as variable name, like str and type in your code.
  • There’s no content of test.txt file, maybe replace it with some text lines in your code to make it an executable script, it will help people to find answer for you.
3周前 评论
cantdo (楼主) 3周前
讨论数量: 2
Jason990420

The length of string.split(sep) will be only 1 if sep not found in string, there’s only item option[i][0], no item option[i][1], that’s why you got exception IndexError: list index out of range.

It is something like this

def Option():
    defoption = list()
    for i in range(count):
        defoption.append(result[i])
    for i in range(count):
        option.append(defoption[i].split("$;$"))
        index = option[i][0].find("\"") + 1
        optionA.append(option[i][0][index:])
        if "$;$" not in defoption[i]:
            print(f'Exception for "$;$" not in {repr(defoption[i])}')
            print(f'option[{i}] is {option[i]} with length {len(option[i])}')
        optionB.append(option[i][1])

option  = []
optionA = []
optionB = []
result  = ['123$;$456', '123$;$456', '123:::456', '123$;$456']
count = len(result)
Option()
Exception for "$;$" not in '123:::456'
option[2] is ['123:::456'] with length 1
Traceback (most recent call last):
  File "<module2>", line 19, in <module>
  File "<module2>", line 12, in Option
IndexError: list index out of range

Note:

  • Not to use Python keyword as variable name, like str and type in your code.
  • There’s no content of test.txt file, maybe replace it with some text lines in your code to make it an executable script, it will help people to find answer for you.
3周前 评论
cantdo (楼主) 3周前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!