Functional programming of basic Python functions

Source: Internet
Author: User

One. Anonymous functions

An anonymous function is a specified function that does not need to be displayed, and frees up memory space as soon as it runs once.

The main forms of expression are:

Lambda Parameters: Specific functions

def Calc (n):     return n**nprint(calc# to anonymous function lambda n:n** N Print (Calc (10))

  You may say that it is not convenient to use this thing. Oh, if it is so used, there is no yarn improvement, but the anonymous function is mainly used with other functions, as follows

res = map (lambda x:x**2,[1,5,7,4,8]) for in Res:    print(i)

Output
1
25
49
16
64

l=[3,2,100,999,213,1111,31121,333]print(max (l)) dic={'K1' : Ten,'K2': +,'k3': $Print (Max (DIC)) Print (Dic[max (dic,key=Lambda k:dic[k]))

Two. Functional programming

  1. Higher-order functions

Any one of the following two features is a higher-order function:

(1) The passed-in parameter of the function is a functional name

(2) The return value of a function is a functional name

def foo ():
Print ("from the Foo")
def test (func):
return func

res = Test (foo)
Res ()

foo = Test (foo)
Foo ()

2. Functional programming: function = function of programming language definition + function of mathematical meaning

In layman's terms, the function is to use the programming language to implement mathematical functions. In this function, the object is immutable, either the parameter is a function, or the return value is a function, there is no for and while loop, all loops are implemented by recursion, no variable assignment (that is, without the variable to save the state), no assignment is not changed.

3.

array=[1,3,4,71,2]ret=[] forIinchArray:ret.append (i**2)Print(ret)#If we have 10,000 lists, then you can only define the above logic as a functiondefmap_test (Array): RET=[]     forIinchArray:ret.append (i**2)    returnretPrint(Map_test (array))#If our needs change, not to put each element in the list squared, plus 1, minus one, then you candefadd_num (x):returnX+1defmap_test (Func,array): Ret=[]     forIinchArray:ret.append (func (i))returnretPrint(Map_test (add_num,array))#You can use anonymous functionsPrint(Map_test (LambdaX:x-1, array))#this is the function of the map function, and the result of the map is that the object can be iteratedPrint(Map (LambdaX:x-1,range (5))) map function
map Function

4.

 fromFunctoolsImportReduce#Merge, get a result of mergingarray_test=[1,2,3,4,5,6,7]array=range (100)#error, RES does not specify an initial valuedefreduce_test (Func,array): l=list (array) forIinchL:res=func (res,i)returnRes#Print (Reduce_test (lambda x,y:x+y,array))#You can pop the first value from the left of the listdefreduce_test (Func,array): l=List (array) res=l.pop (0) forIinchL:res=func (res,i)returnResPrint(Reduce_test (Lambdax,y:x+Y,array))#we should support the user to pass in the initial value themselvesdefReduce_test (func,array,init=None): l=list (array)ifInit isNone:res=l.pop (0)Else: Res=Init forIinchL:res=func (res,i)returnResPrint(Reduce_test (Lambdax,y:x+Y,array))Print(Reduce_test (Lambdax,y:x+y,array,50)) Reduce function
Reduce function

5.

#The movie Theater gathered a bunch of idiots watching movies BB, let's find out what theymovie_people=['Alex','Wupeiqi','Yuanhao','Sb_alex','Sb_wupeiqi','Sb_yuanhao']defTELL_SB (x):returnX.startswith ('SB')deffilter_test (Func,array): Ret=[]     forIincharray:iffunc (i): Ret.append (i)returnretPrint(Filter_test (tell_sb,movie_people))#function filter to return an iterative objectPrint(Filter (LambdaX:x.startswith ('SB') , movie_people)) filter function
Filter Function
#of course, map,filter,reduce, you can handle all data types.Name_dic=[    {'name':'Alex',' Age': 1000},    {'name':'Wupeiqi',' Age': 10000},    {'name':'Yuanhao',' Age': 9000},    {'name':'Linhaifeng',' Age': 18},]#filter out the Millennium King by using filter eight, the turtle, and a 9,000-year-olddeffunc (x): Age_list=[1000,10000,9000]    returnx[' Age'] not inchAge_listres=filter (Func,name_dic) forIinchRes:Print(i) Res=filter (Lambdax:x[' Age'] = = 18, Name_dic) forIinchRes:Print(i)#reduce is used to calculate 1 to 100 and fromFunctoolsImportReducePrint(Reduce (LambdaX,y:x+y,range (100), 100))Print(Reduce (LambdaX,y:x+y,range (1,101)))#use map to process the list of strings, and turn everyone in the list into SB, for example ALEX_SBname=['Alex','Wupeiqi','Yuanhao']res=map (Lambdax:x+'_SB', name) forIinchRes:Print(i) Summary
Summary

Functional programming of basic Python functions

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.