【问题标题】:How to Make a Highscore list with the Score and Name of the Player [duplicate]如何使用玩家的分数和姓名制作高分列表[重复]
【发布时间】:2018-12-27 12:16:16
【问题描述】:

我正在制作一个高分模块,目前只显示获得的前 5 名分数,我希望能够像我目前一样显示这些分数,但也显示与该分数相关联的名称,如何我会这样做吗?

这是我目前的代码:

def highscore():


   file_highscore = open('scores_test2.txt' , 'r')
   scores_and_names = []
   scores = []
   scores_2 = []
   names = []
   for line in file_highscore.readlines():
      score_info = line.split()

      scores_and_names.append(line)
      scores_2.append(scores_and_names[line][])

      scores.append(score_info[1])
      names.append(score_info[0])


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



   print('The First 5 Highscores are:')
   for item in scores[:5]:

      print(item)

任何帮助将不胜感激,因为我需要将此代码用于学校作业。

【问题讨论】:

  • 到目前为止你尝试过什么? “scores_test2.txt”中的一行是什么样的?
  • 将您的高分存储为字典 - 在欺骗here 中查看我的答案 - 字典更适合存储键:值项。还有其他存储它们的方法 - 请参阅其他答案(Json、Pickle、...)

标签: python python-3.x


【解决方案1】:

我们来了

scores = []
with open('scores.txt') as f:
    for line in f:
        name, score = line.strip().split()
        scores.append ((name, int(score)))

    # get top 5
    sorted_scores = sorted(scores, key=lambda x: x[1], reverse=True)

    print('The First 5 Highscores are:')
    for item in sorted_scores[:5]:
        print(item)

scores.txt

John 100
Eduard 200
Phil 150
Romeo 500
Mark 50
Ann 1

输出

('Romeo', 500)                                                                  
('Eduard', 200)
('Phil', 150)                                                                   
('John', 100)                                                                   
('Mark', 50) 

【讨论】:

    【解决方案2】:

    您可以做的不是拥有一个包含分数的列表,而是拥有一个包含 (score, name) 的元组列表并按分数对其进行排序。

    def highscore():
       file_highscore = open('scores_test2.txt' , 'r')
       scores = []
       for line in file_highscore.readlines():
          score_info = line.split()
          scores.append((score_info[0], int(score_info[1])))
    
       scores.sort(key = lambda x:x[1], reverse = True)
       print('The First 5 Highscores are:')
       for score, name in scores[:5]:
          print(name, score)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-13
      • 1970-01-01
      • 2017-06-07
      • 1970-01-01
      • 2019-09-21
      • 1970-01-01
      • 2017-01-30
      • 2012-04-21
      相关资源
      最近更新 更多