使用Python对文本文件中特定索引的值进行排序

达拉维德

我正在为一项纸牌游戏工作。这是它的最后一部分。

我需要排序

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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在Linux中使用特定的分隔符对文本文件中的行进行排序

在第 16 列之后使用 bash 中的 p 值对文本文件进行排序

如何使用python对文本文件中的键进行排序

使用Python中的第二列按字母顺序对文本文件进行排序

在Java中对文本文件行进行排序

在python中的文本文件中对值进行排序

按值对文本文件中的行进行排序

如何在python中按姓氏对文本文件中的行进行排序?

使用额外的空格对文本文件中的数据进行排序会在 python 中产生错误

在python3中对文本文件进行排序

如何在python中对文本文件进行排序?

如何使用gedit按字母顺序对文本文件中的行进行排序

尝试使用方括号中的日期对文本文件进行排序

如何使用文本文件中的数字对python中的文本文件进行排序

对文本文件中的特定行使用grep

使用unix排序对文件夹中的数百万个文本文件进行排序

打开一个文本文件,对文本文件进行排序,然后使用 Python 进行保存

Bash:按字节区分大小写的排序命令或使用python sort命令对文本文件进行排序

如何按行对文本文件进行排序

仅使用标准库,按另一列的分组值中的一列的累积总数对文本文件进行排序?

在python中对文本文件中的排序数据项进行分组和计算

如何根据字符代码或ASCII代码值对文本文件进行排序?

Unix - 根据前两列值对文本文件内容进行排序

按第二个值对文本文件进行排序

无法在输出文件中逐行对文本文件输入进行排序

在同时对文本文件进行某些操作之后,如何删除该文本文件中的特定行

按第一列对文本文件进行排序并计数重复python

根据字段中的字符对文本文件进行排序

对文本文件中的数据进行排序和绘图