This article and everyone to share is mainly the Python development of functional programming related content, come together to see it, I hope to learn from you and use this part of the content is helpful.1. Python takes a function as a parameterImportMathdefAdd(x, Y, f):returnF (x) + f (Y)PrintAdd ( -5, 9, ABS)PrintABS ( -5) + ABS (9)PrintAdd (9, MATH.SQRT)2. The map () function in PythonMap () is a Python built-in high-order function that receives a function f and a list, and then, by putting the function f on each element of the list in turn, gets a new list and returns.defFormat_name(s):returnS[0].upper () + s[1:].lower ()PrintMap (Format_name, [' Adam ', ' LISA ', ' BarT '])3.python in the reduce () functionThe reduce () function is also a high-order function built into Python. The reduce () function receives a parameter similar to map (), a function f, a list, but behaves differently from map (), and reduce () functions f must receive two parameters, and reduce () calls function f repeatedly on each element of the list, and Returns the final result value.defF(x, y):returnX + yPrintReduce (f, [1, 3, 5, 7, 9]) # 25defprod(x, y):returnX * yPrintReduce (prod, [2, 4, 5, 7, 12]) # 3360filter () function in 4.pythonThe filter () function is another useful higher-order function built into Python, and the filter () function receives a function f and a list, the function of which is to judge each element, return True or False, filter () root It is determined that the non-conforming elements are automatically filtered out, and a new list of eligible elements is returned.defis_odd(x):returnX% 2 = = 1PrintFilter (is_odd, [1, 4, 6, 7, 9, 12, 17]) # [1, 7, 9, 17]defIs_not_empty(s):returnS andLen (S.strip ()) > 0PrintFilter (Is_not_empty, [' Test ',None, ', ' str ', ' ', ' End ']) # [' Test ', ' str ', ' End ']ImportMathdefIS_SQR(x): R = Int (math.sqrt (x))returnR*r==xPrintFilter (IS_SQR, Range (1, 101)) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]custom sort functions in 5.pythonSorted () is a high-order function that can receive a comparison function to implement a custom sort, the definition of a comparison function is to pass in two elements to be compared x, y, if X should be in front of y, return-1, if x should be at the back of Y, return 1. returns 0 if x and y are equal.PrintSorted ([36, 5, 12, 9, 21]) # [5, 9, 12, 21, 36]defreversed_cmp(x, y):ifX > Y:return-1ifX < y:return1return0PrintSorted ([5, 9, reversed_cmp) # [36, 21, 12, 9, 5]PrintSorted ([' Bob ', ' about ', ' Zoo ', ' credits ']) # [' Credits ', ' Zoo ', ' about ', ' Bob ']defCmp_ignore_case(S1, s2): u1 = S1.upper () U2 = S2.upper ()ifU1 < U2:return-1ifU1 > U2:return1return0PrintSorted ([' Bob ', ' about ', ' zoo ', ' credits '], cmp_ignore_case) # [' About ', ' Bob ', ' credits ', ' Zoo ']return function in 6.pythonPython's functions can not only return data types such as int, str, list, dict, but also return functions!defCalc_sum(LST):defLazy_sum():returnSUM (LST)returnLazy_sumPrintF #PrintF () # 10defCalc_prod(LST):defLazy_prod():defF(x, y):returnX * yreturnReduce (f, LST, 1)returnLAZY_PRODF = Calc_prod ([1, 2, 3, 4])PrintF () # 247.python Closed PackagedefCount(): FS = [] forIinchRange (1, 4):defF():returnI*ifs.append (f)returnFSF1, F2, f3= count ()PrintF1 () # 9PrintF2 () # 9PrintF3 () # 9defCount(): FS = [] forIinchRange (1, 4):defF(j):defg():returnJ*jreturnGR = f (i) Fs.append (R)returnFSF1, F2, F3 = count ()PrintF1 (), F2 (), F3 () # 1 4 9anonymous functions in 8.pythonHigher-order functions can receive functions for parameters, and sometimes we do not need to explicitly define functions, and it is more convenient to pass in anonymous functions directly.PrintMapLambdaX:X * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]) # [1, 4, 9, 16, 25, 36, 49, 64, 81]PrintSorted ([1, 3, 9, 5, 0],LambdaX, Y:-cmp (x, y)) # [9, 5, 3, 1, 0]myabs =LambdaX:-XifX < 0ElseXPrintMyabs (-1) # 1PrintMyabs (1) # 1PrintFilterLambdaS:s andLen (S.strip ()) >0, [' Test ',None, ', ' str ', ' ', ' End ']) # [' Test ', ' str ', ' End ']9. Python in decorator decoratorWhat is an adorner? · Question: · Define a function · Want to dynamically add functionality at run time · And I don't want to change the function of the code decorator. Can greatly simplify the code and avoid writing repetitive code for each function · Print log: @log · Detection performance: @performance · Database transactions: @transaction · URL Routing: @post ('/register ')9-1. Python to write no parameter decoratorPython's decorator is essentially a high-order function that takes a function as an argument and then returns a new function.defLog(f):deffn(x):Print' Call ' + f.__name__ + ' () ... ' # call factorial () ...returnF (x)returnFn@logdeffactorial(n):returnReduceLambdaX,y:x*y, Range (1, n+1))PrintFactorial (10) # 3628800Print' \ n 'ImportTimedefPerformance(f):def fn(*args, **kw): T1 = time.time () R = f (*args, **kw) t2 = Time.time ()Print' Call%s () in%fs '% (f.__name__, (T2-T1)) # call factorial () in 0.001343sreturnRreturnFn@performancedeffactorial(n):returnReduceLambdaX,y:x*y, Range (1, n+1))PrintFactorial (10) # 36288009-2. Python write with parameter decoratorImportTimedefPerformance(unit):defPerf_decorator(f):defwrapper(*args, **kw): T1 = time.time () R = f (*args, **kw) t2 = time.time () t = (t2-t1) * 1000ifunit== ' MS 'Else(T2-T1)Print' Call%s () in%f%s '% (f.__name__, T, Unit) # Call factorial () in 1.250982 msreturnRreturnWrapperreturnPerf_decorator@performance (' Ms ')deffactorial(n):returnReduceLambdaX,y:x*y, Range (1, n+1))PrintFactorial (10) # 36288009-3. Python Perfect Decorator@decorator can dynamically realize the increase of function function, however, after @decorator "transformation" function, compared with the original function, there is no other place than the function of a little more?defF1(x):PassprintF1.__NAME__ # F1defLog(f):defwrapper(*args, **kw):Print' Call ... 'returnF (*args, **kw)return[Email protected]defF2(x):PassprintF2.__NAME__ # WrapperImportTime, FunctoolsdefPerformance(unit):defPerf_decorator(f): @functools. Wraps (f)defwrapper(*args, **kw): T1 = time.time () R = f (*args, **kw) t2 = time.time () t = (t2-t1) * 1000ifunit== ' MS 'Else(T2-T1)Print' Call%s () in%f%s '% (f.__name__, T, Unit)returnRreturnWrapperreturnPerf_decorator@performance (' Ms ')deffactorial(n):returnReduceLambdaX,y:x*y, Range (1, n+1))PrintFACTORIAL.__NAME__ # factorialten. Python Partial functionsWhen a function has many parameters, the caller needs to provide multiple arguments. If you reduce the number of parameters, you can simplify the burden on the caller.ImportFunctoolssorted_ignore_case = functools.partial (sorted, Cmp=lambda S1, s2:cmp (S1.upper (), S2.upper ())) Print Sorted_ Ignore_case ([' Bob ', ' about ', ' zoo ', ' credits ']) # [' About ', ' Bob ', ' credit ', ' Zoo '] Source: Blog Park
Functional programming of Python learning