仅显示一个人最近 3 个分数中的最高分,保存在 .txt 文件中 [英] Displaying only the highest of a person's 3 most recent scores, saved in a .txt file
问题描述
我正在尝试学习将 Python 用于个人项目的基础知识.
I am trying to learn the fundamentals of using Python for a personal project.
我创建了一个程序,向用户询问十个地理问题,然后将他们的分数保存到一个 .txt 文件中,格式如下:
I have created a program which asks the user ten geographical questions, and then saves their score to a .txt file, in this format:
Imran - 8
Joeseph - 10
Test1 - 6
Test2 - 4
Joeseph - 5
Aaron - 4
Test1 - 1
Zzron - 1
Joeseph - 3
Test1 - 10
Joeseph - 4
然后我创建了一个新程序,可以用来按字母顺序显示每个人的最高分:
I then created a new program, which can be used to display the highest score of each person in alphabetical order:
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 的分数将显示为:
I would like to alter this code, such that it only outputs the highest of a person's 3 most recent scores. For example, from the .txt file given, Joeseph's score would be displayed as:
Joeseph - 5
该程序应省略除每个人最近的 3 个分数之外的所有分数.
The program should omit all but the 3 most recent scores from each person.
推荐答案
与其在第一个 for 循环中跟踪最高分,只需跟踪最后三个分数:
Instead of keeping track of the highest score in your first for loop, just keep track of the last three scores:
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
然后在最后,通过并获得最大值:
Then at the end, go through and get the maximum:
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
然后你可以像以前一样打印出高分:
Then you can print out the high scores as before:
for name in sorted(user_scores):
print(name, '-', user_scores[name])
这篇关于仅显示一个人最近 3 个分数中的最高分,保存在 .txt 文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!