码迷,mamicode.com
首页 > 编程语言 > 详细

有关lambda函数在python中的作用

时间:2014-12-15 12:03:27      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:http   io   ar   sp   for   on   bs   cti   ad   

http://stackoverflow.com/questions/8966538/syntax-behind-sortedkey-lambda

 

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 whileforif 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.

有关lambda函数在python中的作用

标签:http   io   ar   sp   for   on   bs   cti   ad   

原文地址:http://www.cnblogs.com/hope100/p/4164455.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!