2017-08-27 53 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