仅显示一个人的3个最新分数中的最高者,保存在.txt文件中

发布于 2021-01-29 17:29:43

我正在尝试学习将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个最新分数以外的所有分数。

关注者
0
被浏览
47
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    不用跟踪第一个for循环中的最高得分,而只需跟踪最近的三个分数即可:

    user_scores = {}
    for line in scores:
        name, score = line.rstrip('\n').split(' - ')
        score = int(score)
        if name not in user_scores:
            user_scores[name] = []       # Initialize score list
        user_scores[name].append(score)  # Add the most recent score
        if len(user_scores[name]) > 3:   
            user_scores[name].pop(0)     # If we've stored more than 3, get rid of the oldest
    

    然后最后,获得最大收益:

    user_high_scores = {}
    for name in user_scores:
        user_high_scores[name] = max(user_scores[name])   # Find the highest of the 3 most recent scores
    

    然后,您可以像以前一样打印出高分:

    for name in sorted(user_scores):
        print(name, '-', user_scores[name])
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看