0

我正在开发一款游戏,我需要为其添加排行榜。我编写了一个允许用户添加高分、查看高分和删除所有高分的代码。现在我需要按照从高到低的顺序对所有分数进行排序。这是我目前的代码[注意:我知道这不是最好的菜单,但我稍后会更改]:

choice = input(str("Would you like to add a high score to the leader board?: "))
if choice == "y":
    user1 = input(str("Enter username 1: "))
    hs1 = input(str("Enter high score: "))
    user2 = input(str("Enter username 2: "))
    hs2 = input(str("Enter high score: "))
    data1 = user1 + ": " + hs1
    data2 = user2 + ": " + hs2
    with open("leaderboard.txt","a") as file:
        file.write(data1)
        file.write("\n")
        file.write(data2)
        file.write("\n")
        print("Data added.")
elif choice == "n":
    final_list = []
    with open("leaderboard.txt","r") as file:
        first_list = file.readlines() 
        for i in first_list: 
            final_list.append(i.strip())
        print("Leader board")
        print("-------------")
        for count in range(0,len(final_list)):
            print(final_list[count])

else:
    with open("leaderboard.txt","w") as file:
        file.write(" ")
        print("leader board cleared.")

一旦订购了这样的东西,我希望显示排行榜:

1. James F: 32
2. Harris W: 18
3. Courtney J: 12

感谢您的阅读!

4

1 回答 1

0

我发现我可以首先使用数字数据重新构建数据保存到文本文件的方式,如下所示:

user1 = input(str("Enter username 1: "))
    hs1 = input(str("Enter high score: "))
    user2 = input(str("Enter username 2: "))
    hs2 = input(str("Enter high score: "))
    data1 = hs1 + " - " + user1
    data2 = hs2 + " - " + user2

现在数据以数字开头,我可以简单地.sort在我的列表中使用来对它们进行排序,但是它们将按从低到大的顺序排序,所以我不得不使用.reverse()来翻转列表。

于 2019-11-30T19:39:20.927 回答