列表始终被重置?

时间:2017-08-27 16:45:58

标签: python list

所以基本上,我有以下文本文件,其中包含一些学生的姓名和成绩,我需要使用字典来计算他们的平均分数,其中键是他们的名字,值是他们的分数列表。我有以下代码。然而,在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

1 个答案:

答案 0 :(得分: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