【发布时间】:2025-12-04 13:35:01
【问题描述】:
我正在尝试从输入中创建单词保护程序和阅读器(类似于字典) 我的代码:
if path.exists("data/inputs/" + word2 + ".txt"):
file = open("data/inputs/" + word2 + ".txt", "r")
for line in file:
fields = line.split("; ")
field1 = fields[0]
answer=[field1]
if fields[1]!="":
field1 = fields[1]
answer = [field1, field2]
错误:
if fields[1]!="":
IndexError: list index out of range
我尝试使用范围执行此操作,但出现错误“必须是 int 或索引”, 您能告诉我如何使用这些索引并使其正常工作吗?
【问题讨论】:
-
显然有一行只有一个字段...检查您的输入,并在访问索引之前检查
fields的长度。
标签: python arrays python-3.x indexing text