Python 如何修复索引器错误:尝试将csv文件拆分为字典时列表索引超出范围?
我正在执行此任务,但错误索引器错误:列表索引超出范围。它包括按“,”分割CSV文件并将其移动到字典中Python 如何修复索引器错误:尝试将csv文件拆分为字典时列表索引超出范围?,python,python-3.x,Python,Python 3.x,我正在执行此任务,但错误索引器错误:列表索引超出范围。它包括按“,”分割CSV文件并将其移动到字典中 for line in f: parts=line.split(",") quiz[parts[0]]=[parts[1],parts[2].strip("\n")] 完整代码: quiz={} f=open("questions.txt","r") quiz=f.readline() for line in f: parts=line.split(",")
for line in f:
parts=line.split(",")
quiz[parts[0]]=[parts[1],parts[2].strip("\n")]
完整代码:
quiz={}
f=open("questions.txt","r")
quiz=f.readline()
for line in f:
parts=line.split(",")
quiz[parts[0]]=[parts[1],parts[2].strip("\n")]
for i in range(10):
print(quiz)
ans=input("Input your answer")
if ans==quiz[parts[4]]:
print("Correct!")
else:
print("Nope, the answer is")
f.close()
我希望CSV文件被拆分并放在字典中,但它却出现了错误消息
quiz[parts[0]]=[parts[1],parts[2].strip("\n")]
IndexError: list index out of range
注:
以下是questions.txt:
Which birthstone is associated with the month of May?,Diamond,Ruby,Emerald,Sapphire,
C
Which two colours as on the flag of Poland?,Red and Green, Blue and White, Green and White, Red and White,
D
另外,如果可能的话,我希望在没有csv库的情况下解决这个问题,但是如果使用csv库更容易,那也没关系您的输入csv中有多少列?格式正确吗?你能把它包括在这里吗 我建议使用csv库,特别是DictReader函数,而不是readline。这将在csv中直接读取到字典中:
导入csv
打开('names.csv')作为csvfile:
reader=csv.DictReader(csvfile)
对于读取器中的行:
打印(第['first_name']行,第['last_name']行)
f、 关闭()
将first\u name
和last\u name
替换为各自的列标题
编辑:
刚刚看到你关于不使用csv库的通知。csv中似乎没有换行符或标题,因此您可以尝试:
将open('questions.txt')作为f:
对于f中的行:
csvvalues=line.split(',')
打印(CSV值)
这应该打印出您正在读取的值,然后您可以将它们分配给字典中的键:
csvdict={
“csv\u info\u one”:csv值[0]
}
我猜测csv行中的最后一个值是指问题索引,因此这应该适用于良好的词典结构:
将open('questions.txt')作为f:
问题={}
对于f中的行:
csvvalues=line.split(',')
csvvalues=[x.rstrip()表示csvvalues中的x]
问题[CSV值[-1]]={
“Q”:CSV值[0],
“A”:CSV值[1:len(CSV值)-1]
}
打印(问题)
这使得假设问题索引是csv行中的最后一个值,问题是第一个值,可能的答案是第一个和最后一个值之间的剩余值。如果访问超出其内容的列表,则会出现索引器:
a = [1,2,3]
print(a[99]) # IndexError, has only indexes 0,1,2
您可以捕获错误:
try:
print(a[99])
except IndexError:
print("Item doesnot exist") # this is printed
或者先查看您的列表:
if len(a)>=100:
print(a[99]) # would avoid the error
如果数据长度不相等,或者如果您在最后一行之后读取该行,\n且该行为空,并且您拆分/访问该行的次数不多,则读取CSV通常会出现此类错误
您可能希望稍微重新构造代码,并使用namedtuples以提高清晰度: 创建数据:
q = "questions.txt"
with open(q,"w") as f:
f.write("""Which birthstone is associated with the month of May?,Diamond,Ruby,Emerald,Sapphire,
C
Which two colours as on the flag of Poland?,Red and Green, Blue and White, Green and White, Red and White,
D
""") # your problem is probably here, line is read and split and accessed on [0] etc.
# it has no data in it -> IndexError
测验代码:
from collections import namedtuple
QuizRecord = namedtuple('Quiz', 'question,a1,a2,a3,a4,solution')
# this creates a namedtuple with fields for
# question
# a(nswer)1 a(nswer)2 a(nswer)3 a(nswer)4
# solution
Q = []
pos = {"A":1, "B":2, "C":3, "D":4} # map solution letter to position in parts,
# 0 would be the question
with open(q) as f:
for line in f:
parts=line.strip("\n,").split(",")
if not parts:
print("Done reading lines")
break # done reading
# get the next line and get the correct solution from parsed parts
sol = pos.get(next(f).strip("\n,"),-1)
if sol == -1:
print("Done reading lines")
break # done reading
# add a new namedtuple to our quizzes
parts.append(parts[sol]) # add solution as text to ease comparisons
Q.append(QuizRecord._make(parts)) # add a new namedtuple to Q using parts
for question, a1, a2, a3, a4, sol in Q:
print(question)
print("Solutions: ", ' '.join( (a1,a2,a3,a4) ))
ans = input("Input your answer: ").lower()
if ans == sol.lower():
print("Correct!\n")
else:
print(f"Nope, the answer is {sol}\n")
输出:
Which birthstone is associated with the month of May?
Solutions: Diamond Ruby Emerald Sapphire
Input your answerEmerald
Correct!
Which two colours as on the flag of Poland?
Solutions: Red and Green Blue and White Green and White Red and White
Input your answerRed and Green
Nope, the answer is Red and White
文件:
- 及
打印
功能检查索引器
之前的零件
实际是什么。第一行的部分可能少于3个元素,您必须跳过它或单独处理它。因此,您注意到您做了quick={}
以生成一个与代码其余部分一致的dict,但您也做了quick=f.readline()
,这将quick
变成一个字符串。如果您修复了列表索引导致的索引器
,您将很快遇到类型错误
,因为您试图分配给字符串对不起,我是Python新手。您的代码输出:{':{'Q':'波兰国旗上有哪两种颜色?','A':['红色和绿色','蓝色和白色','绿色和白色','红色和白色']},'C':{'Q':'C','A':[]},'D':{'Q':'D','A':[]}这是因为CSV输入文件的格式。你能链接到这个文件吗?我在代码中假设了很多关于输入文件的东西。如果你在阅读时打印输入,你可以设计一个更好的字典结构。哪种诞生石与5月份有关?钻石、红宝石、翡翠、蓝宝石、C(此处换行)波兰国旗上的哪两种颜色?红色和绿色、蓝色和白色、绿色和白色,红色和白色这是一个文件:你可以构造字典,但最好是这样。这就是索引错误的来源。当CSV被读入时,它们被读入csvvalues变量。其中,索引0表示哪个诞生石与5月份相关,1表示钻石,2表示红宝石,3表示蓝宝石,4表示C,您可以从中构造合适的字典结构。