簡體   English   中英

如何修復IndexError:嘗試將csv文件拆分成字典時列出索引超出范圍?

[英]How to fix IndexError: list index out of range when trying to split up a csv file into a dictionary?

我正在執行此分配,但始終使錯誤IndexError:列表索引超出范圍。 它涉及通過“,”分割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

注意:

這是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中有幾列? 格式正確嗎? 你可以在這里包括嗎?

我建議不要使用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行中的最后一個值,問題是第一個,並且可能的答案是第一個和最后一個之間的其余值。

如果您訪問超出其內容的列表,則會發生IndexError:

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

文檔:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM