在 Python 中使用 sorted()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12791923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using sorted() in Python
提问by Programming Noob
Possible Duplicate:
Syntax behind sorted(key=lambda :)
I was going through the documentationand came across this example:
我正在阅读文档并遇到了这个例子:
> student_tuples = [
('john', 'A', 15),
('jane', 'B', 12),
('dave', 'B', 10), ]
> sorted(student_tuples, key=lambda student: student[2]) # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
What I don't understand is what are lambda and student here? Can they be replaced by any other names? And what the :do in student:student[2]? It's a little ambiguous since I've never come across this before.
我不明白的是这里的 lambda 和 student 是什么?可以用其他名字代替吗?和什么:做的student:student[2]?这有点模棱两可,因为我以前从未遇到过这种情况。
采纳答案by senderle
Semantically, this:
从语义上讲,这是:
print sorted(student_tuples, key=lambda student: student[2])
is the same as this:
与此相同:
def sort_key(student):
return student[2]
print sorted(student_tuples, key=sort_key)
lambdajust provides an alternative syntax for function definition. The result is a function object, just like the one created by def. However, there are certain things that lambdafunctions can't do -- like defining new variables. They're good (depending on who you ask) for creating small one-use functions, such as this one.
lambda只是为函数定义提供了另一种语法。结果是一个函数对象,就像由def. 然而,有些事情是lambda函数不能做的——比如定义新变量。它们非常适合(取决于您要求的对象)创建小型的一次性功能,例如这个功能。
Once you understand that, then all you have to know is that keyaccepts a function, calls it on every value in the sequence passed to sorted, and sorts the values according to the order that their corresponding keyvalues would take if they were sorted themselves.
一旦你理解了这一点,那么你所需要知道的就是key接受一个函数,在传递给 的序列中的每个值上调用它sorted,并根据它们对应的key值在自己排序时所采用的顺序对这些值进行排序。
回答by Mark Ransom
lambdais a way to define a function inline, and the part before the colon :is the parameter to the function; in this case it's called student. In this example the function is simply returning the third part of the list or tuple passed to it, which is the age.
lambda是一种定义函数内联的方式,冒号前的部分:是函数的参数;在这种情况下,它被称为student. 在这个例子中,函数只是返回传递给它的列表或元组的第三部分,即年龄。

