您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

不用跟踪第一个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])
其他 2022/1/1 18:48:13 有611人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶