0

我正在尝试将分数写入外部文件,然后查看按分数排序的前 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

我正在尝试对其进行排序,因此最高分排在第一位,因此如果有人可以提供帮助,我将不胜感激。

4

2 回答 2

1

您发布的内容可能希望将您的分数转换为 int,如下所示:

for line in f:                     #reads in the scores from the file and add them to the list
    scores.append(int(line.strip()))

请注意,如果存在不完全由整数组成的分数,这将崩溃。float 如果您的分数包含小数点,您也可以改用。

如果数据类型是int分数,则将按值排序,而不是按字典顺序排序。

或者,您可以使用排序中的键:

scores.sort(key=int, reverse=True)

这不会修改您的数组,而是按预期对它们进行排序。如果任何数字不是有效整数,这将再次崩溃。同样,您可以用浮点数替换 int 小数点。

于 2021-02-04T08:22:06.783 回答
0

当您从文件中读取行时,您的数字将转换为字符串,这会打乱您的数字排序(您不想要词法排序)。您需要将它们转换回数字:

scores.append(int(line.strip()))
于 2021-02-04T08:24:01.857 回答