列表总是被重置?

2024-04-27 04:01:08 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags:
thenameinindexif孩子分数outfile
1条回答
网友
1楼 · 发布于 2024-04-27 04:01:08

您可以使用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

相关问题 更多 >