不确定所有代码都在做什么,但是使用defaultdict并将所有分数存储在一个列表中会更容易求和和平均,如果该键不存在,defaultdict将添加名称并追加,如果该键不存在,则只追加每个分数,它比使用dict.setdefault更有效:from collections import defaultdict
diction1 = defaultdict(list)
averages_dct = {}
student_average = {}
while choice == 'av': #
if schClass == '1': # not sure what this is supposed to do
schClass = open("scores1.txt", 'r')
with open("scores1.txt") as f:
for li in f: # just iterate over the file object
name, score = li.split(":") # split once and unpack
# append score cast as int to the list
diction1[name].append(int(score))
# now average scores for each using calling sum on lists of ints
for name,scores in diction1.items():
student_average = sum(scores) / len(scores)