Python-based-LAMBDA expressions and ternary operations

Source: Internet
Author: User

One, lambda expression

1>>>defAdd (x, y):#Define an addition function2     returnX+y#returns the added value of two parameters3 4>>> z=f (3,4)                5>>>Print(z)67#Call the addition function to return 77>>>Lambdax,y:x+y8<function <Lambda> at 0x0000020f385b86a8>9 #you can see that the lambda is a function class objectTen>>> f=LambdaX,y:x+y#function implementation is the same as add (x, y) One>>> F () A3 ->>> F (3,4) -7 the>>>defmultiply (x, y): -     returnx*y -  ->>> Multiply (3,4) +12 ->>> multiply=Lambdax,y:x*y +>>> Multiply (3,4) A12 at>>>defsubtract (x, y): -     returnX-y -  ->>> Subtract (3,4) --1 ->>> subtract=Lambdax,y:x-y in>>> Subtract (3,4) --1 to  +>>>defdivide (x, y): -     returnx/y the  *>>> Divide (4,2) $2.0Panax Notoginseng>>> divide=Lambdax,y:x/y ->>> Divide (4,2) the2.0 +  A #the above multiplication function, subtraction function, and division function can all be replaced by lambda expressions, which is more convenient

As you can see from the above, lambda expressions can be conveniently used instead of simple functions.

Two or three-dollar operation

1, see what is ternary operation

2, Python's ternary operation format is as follows:

result= value 1 if x<y else value 2 What does this mean, is the result = value 1 if condition 1 else value 2

1>>>deff (x, y):2     returnX-yifX>yElseABS (xy)3 #if x is greater than Y, it returns an X-y value, otherwise it returns the absolute values of X- y4 5>>> F (3,4)#3<4, does not satisfy the IF condition, it returns the absolute value inside the else6>>> F (4,3)7>>>deff (x, y):8     return1ifX>yElse-19 #if x is greater than Y, it returns an X-y value, otherwise it will return 1.Ten>>> F (3,4)#3 is less than 4, returns-1 One-1 A>>> F (4,3)#4 is greater than 3, returns 1 ->>>

Python-based-LAMBDA expressions and ternary operations

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.