首页 > 解决方案 > 如何修复 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()

标签: listindexingrangeout

解决方案


尝试检查您的文件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

推荐阅读