我正在尝试学习使用Python进行个人项目的基础知识.
我创建了一个程序,向用户询问十个地理问题,然后将其分数保存为.txt文件,格式如下:
Imran - 8
Joeseph - 10
Test1 - 6
Test2 - 4
Joeseph - 5
Aaron - 4
Test1 - 1
Zzron - 1
Joeseph - 3
Test1 - 10
Joeseph - 4
然后我创建了一个新程序,可用于按字母顺序显示每个人的最高分:
with open("highscores.txt", "r+")as file:
file.seek(0)
scores = file.readlines()
user_scores = {}
for line in scores:
name, score = line.rstrip('\n').split(' - ')
score = int(score)
if name not in user_scores or user_scores[name] < score:
user_scores[name] = score
for name in sorted(user_scores):
print(name, '-', user_scores[name])
我想改变这段代码,这样它只能输出一个人最近3分的最高分.例如,从给出的.txt文件中,Joeseph的得分将显示为:
Joeseph - 5
除了每个人最近的3个分数外,该程序应该省略所有分数.