覆盖python.txt文件,仅保存每个Name的最后3个条目

时间:2015-03-18 09:54:35

标签: python

我有一个测验程序可以将用户分数保存到文件中。我有一个功能,查看文件中人名下的所有分数,并输出他们的平均分数,但我需要的是只考虑每个名字的最后3个分数。到目前为止,这是我的代码

with open("highscoresclass1.txt") as f:
d = {}

for line in f:
    column = line.split(":")
    names = column[0]
    scores = int(column[1].strip())

    count = 0
    while count < 3:
        d.setdefault(names, []).append(scores)
        count = count + 1

averages=[]
for name, v in d.items():
    average = (sum(v)/len(v))
    averages.append((name, average))

for name, average in sorted(averages, key=lambda a: a[1], reverse=True):
    print(name, average)

1 个答案:

答案 0 :(得分:0)

with open("highscoresclass1.txt") as f:
d = {}

for line in f:
    column = line.split(":")
    names = column[0]
    scores = int(column[1].strip())

    count = 0
    while count < 3:
        d.setdefault(names, []).append(scores)
        count = count + 1

averages=[]
for name, v in d.items():
    average = (sum(v[-3:])/len(v[-3:]))
    averages.append((name, average))

for name, average in sorted(averages, key=lambda a: a[1], reverse=True):
    print(name, average)

谢谢