按高分排序名称

use*_*677 3 python sorting python-3.x

我想按照他们的分数对名单进行排序.到目前为止我所拥有的是什么

file = open("scores.txt", 'r')
for line in file:
    name = line.strip()
    print(name)
file.close()
Run Code Online (Sandbox Code Playgroud)

我不确定如何对它们进行排序.

这是文件内容:

Matthew, 13
Luke, 6
John, 3
Bobba, 4
Run Code Online (Sandbox Code Playgroud)

我希望输出是什么:

John 3
Bobba 4
Luke 6
Matthew 13
Run Code Online (Sandbox Code Playgroud)

有人可以帮忙吗?

Rya*_*ing 5

您可以使用该.split(',')方法将行拆分为单独的部分,然后使用int()将分数转换为数字.该.sort()方法对列表key进行排序,并告诉它要排序的内容.

scores = []
with open("scores.txt") as f:
    for line in f:
        name, score = line.split(',')
        score = int(score)
        scores.append((name, score))

scores.sort(key=lambda s: s[1])

for name, score in scores:
    print(name, score)
Run Code Online (Sandbox Code Playgroud)

这将为您提供按排序顺序包含(名称,分数)对的元组列表.如果要在它们之间用逗号打印出来(为了保持一致),请将打印更改为print(name, score, sep=', ')

输入文件的读取也可以表示为一(大)行

with open("scores.txt") as f:
    scores = [(name, int(score)) for name, score in (line.split(',') for line in f)]
Run Code Online (Sandbox Code Playgroud)

简要说明key=:

lambda函数是一个匿名函数,即没有名称的函数.当您只需要一个小型操作的功能时,通常会使用这些. .sort有一个可选的key关键字参数,它接受一个函数并使用该函数的返回来排序对象.

所以这lambda也可以写成

def ret_score(pair):
    return pair[1]
Run Code Online (Sandbox Code Playgroud)

你可以写, .sort(key=ret_score) 但因为我们真的不需要其他任何功能,所以没有必要声明它.lambda语法是

lambda <arguments> : <return value>
Run Code Online (Sandbox Code Playgroud)

所以这个lambda需要一对,并返回其中的第二个元素.lambda如果您愿意,可以像常规功能一样保存并使用它.

>>> square = lambda x: x**2 # takes x, returns x squared
>>> square(3)
9
>>> square(6)
36
Run Code Online (Sandbox Code Playgroud)