sorted(key=lambda: ...) 后面的语法 [英] Syntax behind sorted(key=lambda: ...)

查看:34
本文介绍了sorted(key=lambda: ...) 后面的语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太明白 sorted() 参数背后的语法:

key=lambda 变量:变量[0]

lambda 不是任意的吗?为什么 variable 在看起来像 dict 的东西中被声明了两次?

解决方案

key 是一个函数,在它们比较之前将被调用以转换集合的项目.传递给 key 的参数必须是可调用的.

lambda 的使用创建了一个匿名函数(可调用).在 sorted 的情况下,callable 只接受一个参数.Python 的 lambda 非常简单.它真的只能做和返回一件事.

lambda 的语法是单词 lambda 后跟参数名称列表,然后是单个代码块.参数列表和代码块由冒号划定.这与 Python 中的其他构造类似,例如 whileforif 等.它们都是通常具有代码块的语句.Lambda 只是带有代码块的语句的另一个实例.

我们可以比较一下使用 lambda 和 def 来创建函数.

adder_lambda = lambda 参数1,参数2:参数1+参数2def adder_regular(parameter1, parameter2):返回参数1+参数2

lambda 只是为我们提供了一种无需指定名称即可执行此操作的方法.这使得它非常适合用作函数的参数.

variable 在这里使用了两次,因为在冒号的左侧是参数的名称,而在右侧则是在代码块中用于计算某些内容.>

I don't quite understand the syntax behind the sorted() argument:

key=lambda variable: variable[0]

Isn't lambda arbitrary? Why is variable stated twice in what looks like a dict?

解决方案

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.

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.

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.

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 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 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆