Python's anonymous function lambda

Source: Internet
Author: User

Lambda parameter:expression

Where lambda is the declaration of an anonymous function, parameter is the function has parameters, how many, the middle separated by commas, expression is a regular expression

def compute (A,B,FUNC): result = Func (A, b) return resultnum = Compute (11,12,LAMBDA x,y:x+y) print (num)

Method Compute has three parameters, from the encapsulated code can be seen, compute the third argument with a function, and then see the fourth line of code, the expression is x+y, so the contents of the Func parameter is x+y, and need to pass two parameters are X, Y, And look at the second line of code that passed in two parameters is a, b, then result = A + b. Because a = 11,b = 12, so result equals 23, so num equals 23, and the print result is 23.

Here's a look at the extension:

def compute (A,B,FUNC): result = Func (A, b) return resultfunc_new = input ("Enter an anonymous function:") num = Compute (11,12,func_new) PR int (num)

The above code means let's enter a function, so that you want it to be additive, it adds. Subtract if you want it to implement subtraction.

However, it can only be used in the 2.7 version of the above code, 3.6 of the words will not be, because input will be the value you entered into a cameo, that is, "Lambda x,y:x+y", you let a string to achieve this, is not funny? At this point we can use the Eval function, which is a powerful function. It can get rid of this string and make it a function that can be called, the following code

def compute (A,B,FUNC): result = Func (A, b) return resultfunc_new = input ("Enter an anonymous function:") func_new = eval (func_new) num = Compute (11,12,func_new) print (num)


This article is from "Love Zhou Yu" blog, please be sure to keep this source http://izhouyu.blog.51cto.com/10318932/1967315

Python's anonymous function lambda

Related Article

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.