Python self-taught lambda expression

Source: Internet
Author: User

For some Python functions, sometimes we only use one or two times in very few cases, but we need to name the function names when we define them, and we can simplify the code by using lambda without having to consider naming problems.
Example:
The following function calculates twice times the X

>> def doublex (x):
Return 2 * x

>> DoubleX (5)
10
>>
is to use lambda to become
>> g = Lambda x:2 * x//LAMBDA followed by parameter name, colon followed by return value
>> g (5)
10
>>

Two examples of parameters comparison

>> def add (x, y):
return x + y

>> Add (3,4)
7
>> g = lambda x,y:x + y
>> g (3,4)
7
>>

See again for example
Filter (), the function has two parameters, the first one is none or another function, the second is a list, the effect is to put each value in the second argument list in the function of the first argument to evaluate the result, all the results of the value of true into a new list, such as:

>> List (filter (none,[1,0,false,true))
[1, True]//[1,0,false,true] in each value, because the first parameter is none, just look at the first and fourth to true, return the list of two values
>>

Example: Returns an odd number in the list, such as range (10)
The General:

>> def Odd (x):
return x% 2

>> temp = range (10)
>> Show = Filter (odd,temp)
>> list (show)
[1, 3, 5, 7, 9]
Using lambda
>> List (filter (lambda x:x% 2,range (10)))
[1, 3, 5, 7, 9]
>>

Python self-taught lambda expression

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.