【问题标题】:How do I fix the "Index out of range" error in Python?如何修复 Python 中的“索引超出范围”错误?
【发布时间】:2021-09-17 20:44:16
【问题描述】:

我正在尝试从 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()

【问题讨论】:

    标签: list indexing range out


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-13
      • 2019-06-24
      • 2021-05-30
      • 1970-01-01
      • 2019-10-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多