【问题标题】:how to make a ordered leader board in python如何在python中制作有序的排行榜
【发布时间】:2021-08-20 12:07:59
【问题描述】:

我们有一个计算项目,在最后阶段,我必须制作一个有序的排行榜(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() 

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

【问题讨论】:

  • 好的,首先你需要了解python中的元组是有序的,不可更改的。因此,您可能会发现使用列表更容易。

标签: python computer-science leaderboard


【解决方案1】:

据我所知,您希望对从文件“H_Highscore.txt”中读取的分数进行排序,然后按从高到低的顺序将它们打印到控制台。如果您想以更强大的方式做到这一点,有一些要点:
-对输入数据添加测试,以确保用户输入了有效的姓名/分数对,否则之后您将无法对其进行排序(您将收到错误消息)。
-如果你想坚持自己的做事方式而不是我提供的解决方案,你应该使用“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() 

玩弄代码,添加打印以查看每个变量在执行过程中的作用!

编辑:一些小错别字。

【讨论】:

    【解决方案2】:

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

    你应该这样做:

    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

    【讨论】:

      【解决方案3】:

      您正在尝试对字符串进行排序,例如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() 
      

      【讨论】:

        猜你喜欢
        • 2016-10-16
        • 2011-05-15
        • 2020-09-29
        • 2020-09-10
        • 1970-01-01
        • 2022-07-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多