【问题标题】:Python how to sort a tuple (string, int) in numerical order for leaderboardPython如何按排行榜的数字顺序对元组(字符串,整数)进行排序
【发布时间】:2021-06-22 01:40:17
【问题描述】:

我对 python 还很陌生。

所以我有两个文件,我的主要 python 文件(骰子游戏)和一个外部 txt 文件,它将玩家姓名和分数存储在元组(int,string)中

我需要对元组进行数字排序(最高优先),并且只将前 5 个打印到主程序。

我该怎么做?

主要python文件:

    if p1_points > p2_points:
      winner_points = p1_points
      winner_player = p1_correct_login[0]
      winner = (winner_points, winner_player) # creates a tuple (2 sets of data in a single variable)

    elif p2_points > p1_points:
      winner_points = p2_points
      winner_player = p2_correct_login[0]
      winner = (winner_points, winner_player) # creates a tuple (2 sets of data in a single variable)

    print("Well done", winner_player, "you won with", winner_points, "points!") # winner variables 
    are determined by player scores.

    #------------------Store scores in winner txt file------------------
    winner = (winner_points, winner_player)
    file = open('winner.txt', 'a')
    file.write(''.join(str(winner)))
    file.write('\n')
    file.close()

    #----------------------Load, update and sort leaderboard-------------
    file = open("winner.txt", "r")
    leaderboard = [] # Should I pass tuples into a list?

winner.txt 文件:

    (75, 'leroy')
    (50, 'lex')
    (66, 'lex')
    (57, 'lex')
    (73, 'lex')
    (69, 'leroy')
    (71, 'leroy') 
    (76, 'leroy')
    (62, 'leroy')
    (64, 'lex')
    (67, 'lex')
    (60, 'lex')

【问题讨论】:

  • sorted(yourtuples, reverse=True)[:5]?
  • 这就像一个魅力!谢谢 timgeb。

标签: python arrays sorting tuples


【解决方案1】:

如果你问我,我会试着用字典来做。

players = {
   75: 'leroy'
   50: 'lex
   66: 'lex'
   57: 'lex'
   73: 'lex'
   69: 'leroy'
   71: 'leroy'
   76: 'leroy'
   62: 'leroy'
   64: 'lex'
   67: 'lex'
   60: 'lex'
}

您可以使用它进行排序

winner_points.sort()

【讨论】:

  • 感谢您的回答,这看起来很有趣,我会试试这个!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多