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

时间:2015-09-02 10:30:11

标签: python file sorting

我必须将文件排序为人们获得的最高分,最低分,并在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上对它进行排序和显示?

2 个答案:

答案 0 :(得分:2)

如果您有file grades

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

for line in lines:
    print line

答案 1 :(得分:0)

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

因此,对于每一行,您将获得一个类似于:

的元组
('Bob', '1', '10')

然后将此元组附加到名称列表中。然后可以对该列表进行排序。在你的例子中,所有的结果都是10个。但是如果一个是20个呢?

以下显示了一种可能的方法:

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
相关问题