按名称的高分对名称进行排序 [英] Sorting names by their high scores
问题描述
我想按分数对姓名列表进行排序. 到目前为止,我是
I want to sort a list of names by their score. What I have so far is
file = open("scores.txt", 'r')
for line in file:
name = line.strip()
print(name)
file.close()
我不确定如何对它们进行排序.
I'm unsure how to sort them.
这是文件内容:
Matthew, 13
Luke, 6
John, 3
Bobba, 4
我希望输出为:
John 3
Bobba 4
Luke 6
Matthew 13
任何人都可以帮忙吗?
推荐答案
您可以使用.split(',')
方法将一行拆分为单独的部分,然后使用int()
将分数转换为数字. .sort()
方法在适当的位置对列表进行排序,而key
告诉它按什么排序.
you can use the .split(',')
method to split a line into its separate parts, then use int()
to convert the score to a number. The .sort()
method sorts a list in place, and the key
tells it what to sort by.
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)
这将为您提供按排序顺序包含(名称,分数)对的元组列表.如果要打印它们之间并用逗号隔开(以保持一致),请将打印内容更改为print(name, score, sep=', ')
This will give you a list of tuples containing (name, score) pairs in sorted order. If you want to print them out with a comma in between them (to keep it consistent) change the print to print(name, score, sep=', ')
输入文件的读取也可以表示为一行(大)
The reading of the input file can also be expressed as one (big) line
with open("scores.txt") as f:
scores = [(name, int(score)) for name, score in (line.split(',') for line in f)]
key=
的简要说明:
A brief explanation of the key=
:
lambda函数是匿名函数,即没有名称的函数.通常,仅在需要小操作的功能时使用它们. .sort
有一个可选的key
关键字参数,该参数采用一个函数并使用该函数的返回值对对象进行排序.
a lambda function is an anonymous function, that is, a function without a name. You generally use these when you need a function only for a small operation. .sort
has an optional key
keyword argument that takes a function and uses the return of that function in sorting the objects.
因此,该lambda
也可以写为
def ret_score(pair):
return pair[1]
然后您可以编写.sort(key=ret_score)
,但是由于我们实际上并不需要该函数,因此无需声明它. lambda语法为
And you could then write .sort(key=ret_score)
but since we dont really need that function for anything else, its not necessary to declare it. The lambda syntax is
lambda <arguments> : <return value>
因此,此lambda取一对,并返回其中的第二个元素.您可以保存lambda
并根据需要将其用作常规功能.
So this lambda takes a pair, and returns the second element in it. You can save a lambda
and use it like a regular function if you wish.
>>> square = lambda x: x**2 # takes x, returns x squared
>>> square(3)
9
>>> square(6)
36
这篇关于按名称的高分对名称进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!