按文本文件每行上的第二个单词排序,然后显示它



我必须将一个文件按人们获得的最高分排序,到最低分,并在python中显示排序后的版本。我当前的文件是这样的:

Bob: 0 /10
Bob: 1 /10
Jane: 9 /10
Drake: 5 /10
Dan: 4 /10
Josh: 1 /10
Dan: 5 /10
(excluding the empty lines)

如何在python上排序和显示?

如果您有文件 grades:

lines = grades.read().splitlines()
lines.sort(key=lambda line: int(line.split()[1]))
for line in lines:
    print line

您需要编写代码来一次一行地读取文件,跳过任何空白行,并将三个有趣的部分分开。这可以使用正则表达式来完成,该表达式能够从每行提取名称,标记和总数到元组中。

那么对于每一行,你会得到一个像这样的元组:

('Bob', '1', '10')

该元组随后被附加到一个名称列表中。然后可以对这个列表进行排序。在您的示例中,所有结果都是满分10分。但如果20人中只有1人呢?

下面展示了一种可能的方法:

import re
names = []
with open('grades.txt', 'r') as f_input:
    for line in f_input:
        if len(line) > 1:
            names.append(re.match(r'(.*?):s*?(d+)s*?/s*?(d+)', line).groups())
for name, mark, total in sorted(names, key=lambda x: float(x[1]) / float(x[2]), reverse=True):
    print "{} - {} out of {}".format(name, mark, total)

显示如下内容:

Jane - 9 out of 10
Drake - 5 out of 10
Dan - 5 out of 10
Dan - 4 out of 10
Bob - 1 out of 10
Josh - 1 out of 10
Bob - 0 out of 10

最新更新