如何修复 Python 中的 "Index out of range" 错误?

How do I fix the "Index out of range" error in Python?

我正在尝试从包含 6 个项目的列表中创建一条记录。错误告诉我 rec[1] 超出范围。

pay = open("paymast.txt","r")
sal = open("saltyp.txt","w")

heading = pay.readline()

for rec in pay:

    rec = rec.split(",")
    
    id = rec[0]
    name = rec[1]
    gender = rec[2]
    code = rec[3]
    grade = rec[4]
    salary = rec[5]
    salary = salary.strip('\n')
    
    record = id+","+name+","+gender+","+code+","+grade+","+salary

    if int(salary) < 1500 and gender == "M":
        
        sal.write(record)

pay.close()
sal.close()

尝试检查您的文件paymast.txt。我试过一个字符串数组,格式为 "id,name,..." 并且拆分工作正常,它引发 IndexError 的唯一时间是输入格式错误时。

例如:

pay = ["1", "0,ted,male,4,23,1440\n",
       "2,katie,female,1,2,240\n"]
# The first index should raise the error

for rec in pay:
    rec = rec.split(",")

    id = rec[0]
    name = rec[1]
    gender = rec[2]
    code = rec[3]
    grade = rec[4]
    salary = rec[5]
    salary = salary.strip('\n')

    record = id+","+name+","+gender+","+code+","+grade+","+salary
    print(record)

出现错误:

Traceback (most recent call last):
  File "so.py", line 9, in <module>
    name = rec[1]
IndexError: list index out of range