我正在为一项纸牌游戏工作。这是它的最后一部分。
我需要排序
Player 1 has won with 16 cards
Player 2 has won with 18 cards
Player 3 has won with 16 cards
Player 4 has won with 20 cards
Player 5 has won with 18 cards
Player 6 has won with 26 cards
Player 7 has won with 22 cards
Player 8 has won with 16 cards
Player 9 has won with 18 cards
Player 10 has won with 24 cards
进入
Player 6 has won with 24 cards
Player 10 has won with 24 cards
Player 7 has won with 22 cards
Player 4 has won with 20 cards
Player 2 has won with 18 cards
因此,我需要为前5名获胜者(拥有最多纸牌的玩家)创建排行榜。上面的文本是所需的输出。顺便说一句,我必须在外部文本文件中输出此排行榜。
我试过的
我试图这样格式化原始文本:
18 cards:Player 3 has won with 16 cards:Player 4 has won with 20 cards:Player 5 has won with 18 cards:Player 6 has won with 26 cards:Player 7 has won with 22 cards:Player 8 has won with 16 cards:Player 9 has won with 18 cards:Player 10 has won with 24 cards:
完成此操作后,我按每个冒号分割了此输出,并打印了用于分割输出的变量。
我的代码:
filereader = open("winner.txt", "r")
for everyline in filereader:
splittingvariable = everyline.split(":")
print(splittingvariable)
filereader.close()
输出:
['player1 has won with 16 cards', 'player2 has won with 18 cards', 'player3 has won with 16 cards', 'player4 has won with 20 cards', 'player5 has won with 18 cards', 'player6 has won with 26 cards', 'player7 has won with 22 cards', 'player8 has won with 16 cards', 'player9 has won with 18 cards', 'player10 has won with 24 cards', '']
在此之后,我不知道该怎么办。我做了很多尝试来解决这个问题,而不是我展示的结果,但是其中大多数最终都以错误告终。
我将不胜感激任何想法/方式来解决这个问题。
首先,清理最终列表中的空字符串元素,然后使用以下代码:
res = ['player1 has won with 16 cards', 'player2 has won with 18 cards', 'player3 has won with 16 cards', 'player4 has won with 20 cards', 'player5 has won with 18 cards', 'player6 has won with 26 cards', 'player7 has won with 22 cards', 'player8 has won with 16 cards', 'player9 has won with 18 cards', 'player10 has won with 24 cards']
res.sort(key = lambda x: x.split()[4], reverse = True)
print(res[:5])
输出:
['player6 has won with 26 cards',
'player10 has won with 24 cards',
'player7 has won with 22 cards',
'player4 has won with 20 cards',
'player2 has won with 18 cards']
希望是您想要的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句