2017-08-27 98 views
2

基本上,我有以下文本文件,其中包含一些學生的姓名和他們的成績,我需要使用字典來計算他們的平均分數,其中鍵是他們的名字,值是他們分數的列表。我有以下代碼。然而,在while循環中,我重置了valuesList(包含其中一個孩子的分數),並重置它,以便我可以添加下一個孩子的分數,並且分數不會混淆。我嘗試了各種解決方案,但都沒有工作。我不確定爲什麼它會重新添加下一個孩子的分數值,以及它爲什麼只是一個空列表。那麼有什麼幫助? 列表總是被重置?

inFile = open('grades.txt','r') 
outFile = (inFile.read()).split() 
scoresDic = {} 
index = 0 #traverse through the list 
index2 =0 
keysList = [] #store the keys 
valuesList = [] 
for i in range(len(outFile)): 
    if outFile [index] not in keysList and outFile [index].isalpha() == True: #if its a name that hasnt been stored in list already 
     keysList.append (outFile [index]) #add it to the keys 
    index+=1 
index = 0 
while True: 
    if outFile [index2] == keysList [index]: 
     valuesList.append (outFile[index2+1]) #if its the name of one of the boys, add his score the values list 
    index2+=1 

    if index2 == len (outFile): 
     scoresDic [keysList [index]] = valuesList #map the boys name to his list of grades into the dictionary 
     index+=1 
     index2 = 0 
     valuesList [:] =[] #reset the list and variables for next kids name 
    if index == len (keysList): 
     break 
print (scoresDic) 
'''should print (in some order) 
Gilliam 78.75 
Jones 83.0 
Cleese 85.75 
Chapman 95.0 
Idle 91.0 
Palin 85.0 
''' 

.txt文件內容:

Cleese 80 
Gilliam 78 
Jones 69 
Jones 90 
Cleese 90 
Chapman 90 
Chapman 100 
Palin 80 
Gilliam 82 
Cleese 85 
Gilliam 80 
Gilliam 75 
Idle 91 
Jones 90 
Palin 90 
Cleese 88 

回答

3

您可以使用defaultdict

from collections import defaultdict 

d = defaultdict(list) 

for name, grade in [i.strip('\n').split() for i in open('grades.txt')]: 
    d[name].append(float(grade)) 

final_results = {name:sum(grades)/float(len(grades)) for name, grades in d.items()} 

for name, grade in final_results.items(): 
    print(name, grade) 

輸出:

Gilliam 78.75 
Jones 83.0 
Cleese 85.75 
Chapman 95.0 
Idle 91.0 
Palin 85.0 
+0

這是相當不錯的。然而,爲了簡單起見,我會在同一個循環中讀取和解析數據,而不是在那裏進行列表理解。 – AKX

+0

另外,我可以建議在字典理解中使用比'a'和'b'更好的名字:) – AKX

+1

@AKX謝謝您的建議!請參閱我最近的編輯。 – Ajax1234