Go The lambda,filter,map,reduce,apply in Python

Source: Internet
Author: User

1. Lambda

1. Basic form:

LetterNumberName=LAMBDAARGS1,aRGs2,.. . ,aRGsn:exprEssion
Similar to macro definitions in the C language

2. Code

1 Lambda x:x%2==02Lambda x:x<<1
2. Filter

1. Basic form

an s=f ilt er ( fun cti on arr ay) Equivalent to a filter function, where thefunCtion The return value is a Boolean type, aRRay satisfies funCtion element to leave.

2. Code

1 array=[1,2,3,4,5,6,7]2Lambda x:x%2==03 ans=filter ( Isodd,array)4print ans

3. Function prototypes

1 def Filter (Function,array): 2     Ans=[]3for in       array:4         ifis  True:5            ans.append (each)6     return ans
3. Map

1. Basic form

map(funCtion,aRGs) to perform a function operation on the sequence args To get the result sequence.

2. Code

1 array=[1,2,3,4,5,6,7]2Lambda x:x<<13 ans1=map (pow2,array )4print ans1

3. Function prototypes

1 def map (function,array): 2     Ans=[]3for in       array:4        ans.append ( each))5     return  ans
4. Reduce

1. Function prototypes

REDuce(funCtion,aRRay,i nitval) funCtion is a function with two parameters, aRRay is a sequence to be processed,initval is the initial value

2. Code

1 array=[1,2,3,4,5,6,7]2Lambda x,y:x+y3 ans2= reduce (add , array,0)4print ans

3. Function prototypes

1 defreduce (function,array,initval):2TMP =list (array)3     ifInitval isNone:4Ans = list.pop (0)#take the first element of the list and delete5     Else:6Ans =Initval7      foreachinchtmp:8Ans =function (Ans,each)9     returnans;Ten  Oneans2= Reduce (add,array,0)
5. Apply

1. Basic form

APPLY(FUnCtion,(parameter of f u nCtion ) )is used to replace FunCtion ,

2. Code

1 Lambda x,y:x+y2 Apply (add, ())

Go The lambda,filter,map,reduce,apply in 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.