【发布时间】: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