anonymous functions and partial functions of Python

Source: Internet
Author: User

anonymous functions and partial functions

anonymous functions

Python allows you to create anonymous functions using the Lambda keyword, which defines an anonymous function that returns a callable function object with the following syntax:

Lambda arg1, arg2, ...: expression
For example

Lambda a,b=2:a+bprint(Add (3))       #  5Print(add 3, ten)   #  -

Anonymous functions have a relatively strong functional programming style, such as:

foo = [2, 9, 8, +, +]print filter (lambda x:x% 3 = = 0, foo)prin T map (Lambda x:x% 3 = = 0, foo)

Using lambda expressions, you can avoid defining functions, which makes your code more concise.

Partial function

function parameters in Python can have default values, which can reduce the complexity of function calls, such as:

def Add (A, B, c=100):    return a+b+cprint(add (+)  ) #  the

When a function has too many arguments and needs to be simplified, the partial function (functools.partial) can be used to create a new function that can fix some of the parameters of the original function, making it easier to invoke .

 from Import Partial def Add (A, B, c=100):    return a+b+= partial (add, c=100)Print (plus (+))     #  print(plus ( -20))    #  110 

In the above example, partial (add, c=100) uses the keyword parameter c=100, if it is just a simple use of partial (add, 100), then 100 as the positional parameter, will be considered as the fixed value of parameter a. For example:

 from Import Partial def Add (A, B, c=100):    return a+b+= partial (add, +)print( Plus (+)     #  240
Print (plus (40, 50)) # 190

Here, plus (40), the incoming 40 is assigned to B, and C uses the default parameter 100;

anonymous functions and partial functions of Python

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.