python--Functional Programming (high-order functions (map, reduce, filter,sorted), anonymous functions (lambda))

Source: Internet
Author: User
Tags abs iterable

1.1 Functional programming

Process-oriented programming: we can break down complex tasks into simple tasks by splitting large pieces of code into functions through a layer of functions, and this step-by-step decomposition can be called process-oriented programming. function is the basic unit of process-oriented program design.

Functional programming: is to use a series of functions to solve the problem, functional programming is based on the programming paradigm to the desired result, as long as the input is determined, the output is determined.

1.2 Higher order functions

Functions can be passed as arguments, and such functions are called higher-order functions.

1.2.1 function is variable

Use Python's built-in function print () as a column, call the function code

Print ("helloWorld") Hello World # Write print only Print <built-inprint># visible print ("Hello World") is a function call, and print is the function itself 

To get the result of the function call execution, we assign the result to the variable:

>>> AA = ABS ( -20)>>> AA20

If you assign a value to a variable in the function itself

print>>> p<built-inprint># The function itself can be assigned to a variable, and the variable can point to the function 

We call this print function with a variable to verify the result as follows

>>> p ("check") Check

Summary: The function name is also a variable, for the built-in function of print (), it is entirely possible to think of the function name print as a variable, which points to an object that can print anything.

Note: The actual program code must not be written like this, just to illustrate, to restore the print function, please restart the Python interactive environment

1.2.2 Incoming function

A variable can point to a function, a function can receive a variable, and a function may receive another function as a function, a function called a higher order function.

The return value of a function is a function name and a higher order function.

For example: a simple high-order function

def Add (x, y    , z): return ABS (x) += Add (12,23,abs)   # function Execution result assignment to AAprint# View the value of AA #  # Note, the ABS () function is the absolute value of an integer
1.3 Anonymous functions

What is an anonymous function:

In Python, there is an anonymous function lambda, an anonymous function that refers to a function or subroutine that does not need to define an identifier (the function name).

To define a lambda expression:

Lambda   arguments:express    #arguments parameter (can have multiple parameters)#Express Expression # the lambda return value is the address of a function, that is, the function object lambda  arguments:express  #把的到lambda函数地址, Assign to variable AA view this lambda function address   and use AA (argument) to   view the value of this function

Example 1

def PF (x=0):    return x**2print(PF (3))
common function definition, figure square
Lambda x:x**2print(AA (4))#
lambda function to calculate the square of the number

Summarize:

1.LAMBDA functions can have multiple arguments, contain no more than one expression, do not attempt to cram too much into a lambda function, and if you need to do complex functions, define a normal function and define what you want to define.

2.LAMBDA functions are used to encapsulate special, non-reusable code, to avoid flooding our code with a large number of single-line functions.

1.4map function

Map () function, map map

Map (func,iterable)

The map () function accepts two parameters, one is a function, an iterative object (iterable), and map passes the incoming function to each element of the sequence sequentially, returning the result as the result of the new, iterative object.

Example: There is a function, f (x) = x+1 The resulting number plus 1 to function on a [1,2,3,4,5,6]

Number = [1,2,3,4,5,6]#1. Defining a method with a common functiondefAdd_one (x):returnX+1defmap_test (Func,arrey): Res= []     forIincharrey:i=func (i) res.append (i)returnResPrint(Map_test (add_one,number))#[2, 3, 4, 5, 6, 7]#2. The resulting result defined by the lambda function, with the Map_test function defined by 1Print(Map_test (LambdaX:x+1, number))#[2, 3, 4, 5, 6, 7]#3. Use the map () function to definePrint(List (Map (LambdaX:x+1, number)))#[2, 3, 4, 5, 6, 7]#Note: The result of Map () is a iterator, which needs to be computed with a list () function to return a list of the entire sequence.

We might want to write a loop, or we can calculate the result, but to implement multiple functions, it is also possible to write more than one cycle example: the sum of squares of the elements in each list or n times

Map (), as a higher order function, actually abstracts the arithmetic rules, not only to calculate the simple f (x) = X+1, but also to calculate more complex functions.

Summary: Map () processes each element in the sequence, resulting in a iterator, which is required through list (Iteratro), the number of the list element, as in the original position

1.5reduce function

The reduce () function can be used directly in the Python2

The reduce module needs to be called in Python3

 from Import reducereduce (function, sequence, initial=none)  #该函数的默认用法

The reduce function, which sequence the elements of a sequence of functions, each carrying a pair (previous results and elements of the next sequence), continuously adds the existing result and the next effect to the resulting subsequent result, and finally gets our sequence as the return value of the final result.

Number1 = [2,3,4,10]#1. General function Definitiondefchengfa (x, y):returnX*y#returns the result of multiplying by two numbersdefReduce_test (func,seq,init=None):ifInit isNone:res= Seq.pop (0)#seq Deletes the first element and gets to delete this element assignment to res    Else: Res=Init forIinchSeq:res= Func (res,i)#Loop Once, execute the Func function    returnResPrint(Reduce_test (chengfa,number1))# -Print(Reduce_test (chengfa,number1,10))#2400#If the init value is given, it is the result of multiplying the initial value by each element of the list#2.LAMBDA functions, defined with the Reduce_test () functionPrint(Reduce_test (LambdaX,y:x*y,number1,init=3))#720#3. Use reduce (), combined with lambda ()Print(Reduce (Lambdax,y:x*y, Number1))# -gets the list of all elements, multiplied by the result number1= [2,3,4,10]#1. General function Definitiondefchengfa (x, y):returnX*y#returns the result of multiplying by two numbersdefReduce_test (func,seq,init=None):ifInit isNone:res= Seq.pop (0)#seq Deletes the first element and gets to delete this element assignment to res    Else: Res=Init forIinchSeq:res= Func (res,i)#Loop Once, execute the Func function    returnResPrint(Reduce_test (chengfa,number1))# -Print(Reduce_test (chengfa,number1,10))#2400#If the init value is given, it is the result of multiplying the initial value by each element of the list#2.LAMBDA functions, defined with the Reduce_test () functionPrint(Reduce_test (LambdaX,y:x*y,number1,init=3))#720#3. Use reduce (), combined with lambda () fromFunctoolsImportReducePrint(Reduce (Lambdax,y:x*y, Number1))# -
gets the list of all elements, multiplied by the result
Print (Reduce (lambda x,y:x+y,range (1,101)))
get 1-100 of and

1.6filter function

Filter () function for filtering sequences

Like map (), filter () also accepts a function and a sequence (an iterative object, which can be used for loops), unlike map (), where Fillter () acts on each element in turn, The element is then persisted or discarded depending on whether the return value is true or false.

Cases:

AA = ['A',"','B', None,'C','  ']#1. Custom Function TestingdefNot_empty (s):returnS andS.strip ()deffilter_test (func,iter): Res= []     forIinchiter:i=func (i)ifi:res.append (i)returnResPrint(Filter_test (NOT_EMPTY,AA))#[' A ', ' B ', ' C ']#2.filter built-in function testPrint(List (filter (NOT_EMPTY,AA)))#[' A ', ' B ', ' C ']
put the list of empty strings, blank elements, all removed

The key to the filter () function is to implement a filtering function correctly,

Note: the filter () function returns a iterator, memory address, a value that needs to look at the memory address, a list () function, or the value of the address

1.7sorted function

The sorted () function is also a high-order function that can receive key

Sorted sorting, sorting is the size of the comparison element, if the number can be directly compared to if it is a string or two dict (dictionary)?

Sorted () The passed-in parameter is an object that can be iterated, and the object that returns the value is a list

Cases:

AA = [11,-10,20,21,30,-40]print(sorted (AA))
Number Default sort

Receives a key function to implement a custom sort

Example: Sorting by absolute size

AA = [11,-10,20,21,30,-40]print(sorted (aa,key=ABS))#[-10, 11, 20, 21, 30,-40 ]
Sort by absolute value

Example: String sorting

Print (Sorted ("hello")) # [' E ', ' h ', ' l ', ' l ', ' O '] Print (Sorted (["hello","ho","haha  "])#  [' haha ', ' hello ', ' ho ']
string Sort

Note: By default, the string sort is compared by the size of the ASCII-encoded table.

Final Summary:

Several high-order functions built into Python: map (), reduce (), filter,sorted ()

python--Functional Programming (high-order functions (map, reduce, filter,sorted), anonymous functions (lambda))

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.