如何在 python 中制作有序的排行榜

how to make a ordered leader board in python

我们有一个计算项目,在最后阶段我必须制作一个有序的排行榜(top5)。然而,这比我想象的更令人困惑。 到目前为止,我已经做到了这一点,但它没有被订购,也没有进入前 5 名。

def leaderboard():
    print ("\n")
    print ("⬇ Check out the leaderboard ⬇") #LEADERBOARD SECTION
    f = open('H_Highscore.txt', 'r')
    leaderboard = [line.replace('\n','') for line in f.readlines()]
    i = 0
    limit = 5
    while i < limit:
        leaderboard_tuples = [tuple(x.split(',')) for x in leaderboard]
        leaderboard_tuples.sort(key=lambda tup: tup[0])
        i+=1
    for i in leaderboard:
        print(i)
    f.close()
    time.sleep(10)

user = str(input("Enter a name: "))
file = open ("H_Highscore.txt", "a")
score = str(input("enter you score: "))
file.write("\n")
file.write(user)
file.write(",")
file.write(str(score)) # (int(x)) can not be written
file.write("pts")
file.write("\n")
file.close()
time.sleep(0.5)
leaderboard() 

如果能得到一些帮助就好了,如果我找不到任何帮助也没关系。

据我所知,您想对从文件“H_Highscore.txt”中读取的分数进行排序,并按照从高到低的顺序将它们打印到控制台。如果您想以更稳健的方式做到这一点,有一些要点:
-在输入数据上添加测试以确保用户输入了有效的name/score对,否则之后你将无法对其进行排序(你会得到一个错误) .
-如果您想坚持自己的做事方式而不是我将提供的解决方案,您应该使用“with open('H_Highscore.txt', 'r') as f”而不是“f = open('H_Highscore.txt', 'r')" 因为 with 语句将确保在出现错误时关闭文件(阅读更多相关信息 here)。
-我更改了你的代码,使其按照我理解的方式工作,但你真的应该好好看看你写入文件的方式以及你的 CLI 工作的整个方式,这样用户就可以与它交互而无需不得不一遍又一遍地 运行 代码,也许添加一个带有 break 变量的 while 循环。

import time

limit = 5 # you can set out the limit here.

def leaderboard():
    scores = [] 
    print ("\n") 
    print ("⬇ Check out the leaderboard ⬇")
    #LEADERBOARD SECTION 
    for line in open('H_Highscore.txt', 'r'):
        name, score = line.split(",")
        score = int(score) # clean and convert to int to order the scores using sort()
        scores.append((score, name))
        
    sorted_scores = sorted(scores, reverse = True) # this will sort the scores based on the first position of the tuples
    
    for register in sorted_scores[:limit]:
        # I will use string formating, take a look at it, it is really usefull.
        text = f"%s: %s pts" % (register[1], register[0])
        print(text)

user = str(input("Enter a name: "))
file = open("H_Highscore.txt", "a")
score = str(input("enter you score: "))
# file.write("\n")
file.write(user)
file.write(",")
file.write(str(score)) # (int(x)) can not be written
file.write("\n")
# file.write("\n")
file.close()
time.sleep(0.5)
leaderboard() 

玩转代码,添加打印以查看每个变量在途中的作用!

编辑:一些小错别字。

您似乎排序了五次并列出了排行榜中的所有项目,而不是排序了一次并列出了前五名。

你应该这样做:

def leaderboard():
    print()
    print("⬇ Check out the leaderboard ⬇") #LEADERBOARD SECTION
    f = open('H_Highscore.txt', 'r')
    leaderboard = [line.strip().split(',') for line in f.readlines()]
    leaderboard.sort(key=lambda item: -int(item[1][:-3]))
    for i in leaderboard[:5]:
        print(i)
    f.close()
    time.sleep(10)

请注意我是如何使用分数的负数将最高分排在第一位的。

我本可以使用:, reverse=True

您正在尝试对字符串进行排序,例如 10pts。关键是将从文本文件中读取的整数的字符串表示形式转换回具有 int() 的整数,然后对其进行排序:

def leaderboard():
    print ("\n")
    print ("⬇ Check out the leaderboard ⬇") #LEADERBOARD SECTION
    f = open('H_Highscore.txt', 'r')
    leaderboard = [line.strip().split(',') for line in f.readlines() if line.strip()]
    leaderboard = [(i[0], int(i[1][:-3])) for i in leaderboard]
    leaderboard.sort(key=lambda tup: tup[1], reverse=True)
    for i in leaderboard[:5]:
        print(i[0], i[1],'pts')
    f.close()
    time.sleep(10)

user = str(input("Enter a name: "))
file = open ("H_Highscore.txt", "a")
score = str(input("enter you score: "))
file.write(f"{user},{score}pts\n")
file.close()
time.sleep(0.5)
leaderboard()