sorted(key = lambda:...)后面的语法 [英] Syntax behind sorted(key=lambda: ...)
问题描述
我不太了解sorted()
参数背后的语法:
I don't quite understand the syntax behind the sorted()
argument:
key=lambda variable: variable[0]
lambda
不是任意的吗?为什么variable
在看起来像dict
的地方重复两次?
Isn't lambda
arbitrary? Why is variable
stated twice in what looks like a dict
?
推荐答案
key
是一个函数,在比较集合的项目之前,将调用该函数来对其进行转换.传递给key
的参数必须是可调用的.
key
is a function that will be called to transform the collection's items before they are compared. The parameter passed to key
must be something that is callable.
使用lambda
会创建一个匿名函数(可调用).在sorted
的情况下,可调用对象仅采用一个参数. Python的lambda
非常简单.它只能做并真正返回一件事.
The use of lambda
creates an anonymous function (which is callable). In the case of sorted
the callable only takes one parameters. Python's lambda
is pretty simple. It can only do and return one thing really.
lambda
的语法是单词lambda
,其后是参数名称列表,然后是单个代码块.参数列表和代码块用冒号表示.这类似于python中的其他构造,例如while
,for
,if
等.它们都是通常具有代码块的语句. Lambda只是带有代码块的语句的另一个实例.
The syntax of lambda
is the word lambda
followed by the list of parameter names then a single block of code. The parameter list and code block are delineated by colon. This is similar to other constructs in python as well such as while
, for
, if
and so on. They are all statements that typically have a code block. Lambda is just another instance of a statement with a code block.
我们可以将lambda与def的使用进行比较,以创建一个函数.
We can compare the use of lambda with that of def to create a function.
adder_lambda = lambda parameter1,parameter2: parameter1+parameter2
def adder_regular(parameter1, parameter2): return parameter1+parameter2
lambda只是为我们提供了一种无需分配名称的方法.这非常适合用作函数的参数.
lambda just gives us a way of doing this without assigning a name. Which makes it great for using as a parameter to a function.
variable
在这里使用了两次,因为在冒号的左手边它是参数名,而在右手边的代码块中正用它来计算某些东西.
variable
is used twice here because on the left hand of the colon it is the name of a parameter and on the right hand side it is being used in the code block to compute something.
这篇关于sorted(key = lambda:...)后面的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!