Python-如何从文本文件打印(问题在下面说明)

问题描述 投票:0回答:1

我有一个外部文本文件,我在其中以以下形式存储名称和分数:

[(名称)具有(分数-整数)分]

一个例子是:鲍勃得25分

我想按原样打印行,但仅从最高得分开始按降序排列前5位。

换句话说,我希望打印出与文本文件中相同的行,但是从该行的最高整数到最低整数(分数)进行排序。我还想将打印的行数限制为5,这意味着仅按降序打印前5个得分。

我已经尝试了很多方法,但最终我得到的是带有引号和括号的分开的名称和分数,但我的目标是按原样打印行。

有人可以帮我吗?

编辑:这是当前需要帮助的代码。

path = "leaderboard.txt"
with open(path, 'r') as f:
    file_lines = f.readlines()
matchscore = [(l.split()[0], int(l.split()[2])) for l in file_lines]
matchscore.sort(key=lambda x: x[1], reverse=True)
print(*matchscore[0:1])
print(*matchscore[1:2])
print(*matchscore[2:3])
print(*matchscore[3:4])
print(*matchscore[4:5])
python python-3.x python-requests python-3.5
1个回答
2
投票

使用分数作为sort的键直接对行进行排序:

path = "leaderboard.txt"
with open(path, 'r') as f:
    file_lines = f.readlines()

file_lines.sort(key=lambda line: int(line.split()[2]), reverse=True)

print('\n'.join(file_lines[:5]))
© www.soinside.com 2019 - 2024. All rights reserved.