我正在尝试将分数写入外部文件,然后查看按分数排序的前 5 个分数。这是我的代码:
def winner_1(total_score_1):
print(player_1 + " is the WINNER!")
Winner_1 = (str(total_score_1) + " points. Scored by " + player_1)
f = open("leaderboard.txt", "a")
f.write(''.join(Winner_1))
f.write('\n')
f.close()
# Subroutine if player 2 wins and to write the score and winners name to external file
def winner_2(total_score_2):
print(player_2 + " is the WINNER!")
Winner_2 = (str(total_score_2) + " points. Scored by " + player_2)
f = open("leaderboard.txt", "a")
f.write(''.join(Winner_2))
f.write('\n')
f.close()
if total_score_1 > total_score_2:
winner_1(total_score_1) #call in the subroutine that player 1 won
elif total_score_2 > total_score_1:
winner_2(total_score_2) #call in the subroutine that player 2 won
else:
tie(total_score_1, total_score_2)
scores = list()
with open('leaderboard.txt', 'r') as f:
for line in f: #reads in the scores from the file and add them to the list
scores.append(line.strip())
f.close()
#sorts the scores in reverese so the highest scores are at the top
scores.sort(reverse = True)
scores_top_5 = scores[0:5] #store the top 5 as a variable
#print the top 5 using a for loop so it shows as a list
i = 1
for x in scores_top_5:
print(i, ".", x) #it shows the position of the player in the leaderboard
i += 1
我正在尝试对其进行排序,因此最高分排在第一位,因此如果有人可以提供帮助,我将不胜感激。