PYTHON-LAMBDA usage

Source: Internet
Author: User

Objective:

A lambda function is also called an anonymous function, that is, the function does not have a specific name.

First, the basic

A lambda statement is actually built as a function object. There is a limit to the anonymous function, that is, there can be only one expression, without writing return, the return value is the result of that expression.

Lambda (a,b:a+b) #关键字lambda表示匿名函数, the colon is preceded by a parameter, can have multiple, separated by commas, and the return value to the right of the colon. 

Lambda Benefits:
1, using Python to write some execution scripts, using lambda can eliminate the process of defining functions, so that the code is more streamlined.
2, for some of the abstract, will not be another place to reuse the function, sometimes to a function name is also a problem, using lambda does not need to consider the problem of naming.
3. Using lambda makes the code easier to understand at some point.

to give a simple example: Def f (x):   return x**2  print f (4= lambda x:x**2print g ( 4)

Second, advanced-built-in functions

1. Map ()
Iterates through the sequence, operates on each element of the sequence, and finally gets a new sequence.

Li = [all] = [123= map (lambda A, b:a + B, Li, SL) print (list (new_list)) Results output as:>>>[, [+]

2. Reduce ()
Cumulative operation for all elements within a sequence

from = [one,three,four = reduce (lambda a,b:a+b,li) # The first parameter of reduce, The function must have two parameters # reduce the second parameter, to loop the third parameter of the sequence # reduce, the initial value of the print (result) output:>>>

3. Filter ()
Filter the elements in a sequence, and finally get a sequence that matches the criteria

Li = [one,one,and the other = filter (lambda a:a>, li) print (list (new_ List) #filter第一个参数为空, the original sequence output will be obtained:>>>[]

Above ~

Python-lambda usage

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.