Python--Lambda expression

Source: Internet
Author: User

Lambda expressions, usually used in situations where a function is required, but do not want to be bothered to name a function , that is, an anonymous function .

The content of the anonymous function represented by Lambda should be simple, and if complex, simply redefine a function, using lambda is a bit too stubborn.

Lambda is used to define an anonymous function, if you want to bind a name to him, it will appear a little superfluous, usually directly using the lambda function. As shown below:

add = lambda x, y : x+yadd(1,2) # 结果为3

So how do you actually use lambda expressions?

1. Application in functional programming

Python provides many features of functional programming, such as map, reduce, filter, sorted, and so on, which support functions as parameters, and lambda functions can be applied in functional programming. As follows:

# 需求:将列表中的元素按照绝对值大小进行升序排列list1 = [3,5,-4,-1,0,-2,-6]sorted(list1, key=lambda x: abs(x))

Of course, it can also be as follows:

list1 = [3,5< Span class= "p" >,-4,-1 ,0,-2 -6]def get_abs  (xreturn abs (x) sorted (list1 ,key=get_abs     

But the code in this way doesn't look enough pythonic

2, applied in the closure

def get_y(a,b): return lambda x:ax+by1 = get_y(1,1)y1(1) # 结果为2

Of course, you can also implement closures with regular functions, as follows:

def get_y(a,b): def func(x): return ax+b return funcy1 = get_y(1,1)y1(1) # 结果为2

This is just a bit verbose.

So is the lambda function clearer than the normal function in any case?

Definitely not.

There is a sentence in the Zen of Python: Explicit is better than implicit (clear is better than obscure), which means that it is clearer in which way, do not blindly use lambda expressions.

Python--Lambda expression

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.