2017-08-27 7 views
2

基本的に、私はいくつかの学生とその成績の名前を持つ次のテキストファイルを持っており、キーが名前で値がそのスコアのリストである辞書を使って平均スコアを計算する必要があります。私は次のコードを持っています。一方、whileループでは、valuesList(子供の1人のスコアを含む)をリセットして、次の子供のスコアを追加できるようにリセットし、スコアが混ざらないようにします。私は様々なソリューションを試しましたが、どれも成功しませんでした。なぜそれが次の子供の得点の価値を再付加するのか、なぜそれが空のリストとして残っているのかは分かりません。だから助け? リストは常にリセットされていますか?

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

関連する問題