不用跟踪第一个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])



