首页 > 解决方案 > 如何修复IndexError:尝试将csv文件拆分为字典时列表索引超出范围?

问题描述

我正在做这个作业,但不断收到错误 IndexError: list index out of range。它涉及通过“,”拆分 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(",")
     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

笔记:

这是问题.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 库的情况下解决这个问题,但如果使用它更容易,那就没问题了

标签: pythonpython-3.x

解决方案


您的输入 csv 中有多少列?格式是否正确?你能把它包括在这里吗?

我建议不要使用 readline,而是使用 csv 库,特别是 DictReader 函数。这将在 csv 中直接读入字典:

import csv
with open('names.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row['first_name'], row['last_name'])
    f.close()

替换first_namelast_name与您各自的列标题。

编辑:

刚刚看到您关于不使用 csv 库的通知。看起来您的 csv 中没有换行符或标题,因此您可以尝试:

with open('questions.txt') as f:
   for line in f:
     csvvalues = line.split(',')
     print(csvvalues)

这应该打印出您正在读取的值,然后您可以将它们分配给字典中的键:

csvdict = {
   'csv_info_one': csvvalue[0]
}

我猜测 csv 行中的最后一个值是指问题索引,所以这应该适用于一个好的字典结构:

with open('questions.txt') as f:
  questions = {}
  for line in f:
    csvvalues = line.split(',')
    csvvalues = [x.rstrip() for x in csvvalues]
    questions[csvvalues[-1]] = {
      'Q' : csvvalues[0],
      'A' : csvvalues[1:len(csvvalues)-1]
    }

  print(questions)

这假设问题索引是 csv 行中的最后一个值,问题是第一个,可能的答案是第一个和最后一个值之间的其余值。


推荐阅读