list - 如何修复 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
推荐阅读
- macos - Reaver 遇到相同的错误:“[!] WPS 事务失败(代码:0x04),重新尝试最后一个 pin”
- authentication - 在页面外调用 AuthenticationStateProvider
- c++ - C++ 高级宏
- c - 如何使新创建的进程成为自己的父进程
- macos - 如何在 mac 上设置多个颤振版本?
- variables - 修改产品列表中的产品数量 Presta Shop 1.7+
- three.js - three.js:投射 SpotLight 阴影
- swift - 将嵌套数组元素结果传递给 @Binding
- python - Dataclass - 为什么属性的处理方式与普通类不同?
- python - 包含 Popen 的模块函数被拒绝但在模块函数之外工作