gpt4 book ai didi

python - 列表总是被重置?

转载 作者:太空宇宙 更新时间:2023-11-04 00:30:52 25 4
gpt4 key购买 nike

基本上,我有以下文本文件,其中包含一些学生的姓名和他们的成绩,我需要使用字典计算他们的平均分数,其中键是他们的姓名,值是他们的分数列表。我有以下代码。然而,在 while 循环中,我重置了 valuesList(包含其中一个 child 的分数)并重置它以便我可以添加下一个 child 的分数并且分数不会混淆。我尝试了多种解决方案,但都没有奏效。我不确定为什么它会重新附加下一个 child 分数的值以及为什么它只是一个空列表。那么有什么帮助吗?

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

最佳答案

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

关于python - 列表总是被重置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45907167/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com