In Python, Lambda uses

Source: Internet
Author: User

Here's an example:

1 func=lambda x:x+12 Print (func (1)) 3 #24 Print (func (2)) 5 #36 7 #以上lambda等同于以下函数8 def func (x): 9     return (x+1)

It can be thought that lambda, as an expression, defines an anonymous function, where code x is the entry parameter and x+1 is the function body. Here Lambda simplifies the writing of function definitions. Code is more concise, but the use of functions is more intuitive and easy to understand.

In Python, there are also several well-defined global functions that are easy to use, filter, map, reduce.

1 from functools import reduce  2 foo = [2,, 9,,, 8,, +] 3  4 print (list (filter (lambda x:x% 3 = =  0, Foo))) 5 #[18, 9,, 6  7 print (list (map (lambda x:x * 2 +, foo)) 8 #[14, 46, 28, 54, 44, 58, 26, 34, 9 Print (Reduce (lambda x, y:x + y, foo) one #139

The role of the map in the example above is very simple and clear. But does Python have to use lambda to make this simple? In the object traversal process, in fact Python for. In.. The IF syntax is already strong and is more readable than lambda.

For example, the map above can be written as: print ([x * 2 + x in Foo]) is very concise and easy to understand.

The filter example can be written as: print ([x for X in foo if x% 3 = = 0]) is also easier to understand than Lambda's way.

In Python, Lambda uses

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.