Python-Functional programming

Source: Internet
Author: User
Tags abs iterable

Python Basics-Functional programming

Higher order functions: Map, reduce, filter,sorted

Anonymous functions: Lambda

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 obtain the desired results, 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 ("Hello World") Hello world# write only print>>> print<built-in function print> #可见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

>>> p = print>>> p<built-in function print> #函数本身可以赋值给变量, variables can point to functions

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 (+abs) AA = Add (12,23,abs)   #函数执行的结果 assigned to Aaprint (AA) #查看aa的值 #35 #注, 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 arguments) #express expression #lambda The return value is the address of a function, that is, the function object AA = Lambda  Arguments:express  #把的到lambda函数地址, assign a value to the variable AA view the lambda function address   and use AA (argument) to   see the value of the function

PS1:

Common function definition, figure square

1 def PF (x=0): 2     return x**23 print (PF (3))

PS2:

Lambda function to calculate the square of the number

1 AA = lambda x:x**22 print (AA (4)) 3 #16

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 normal function def add_one (x):    return x+1def map_test (Func,arrey):    res = [] for    I in Arrey:        i = func (i)        res.append (i)    return Resprint (Map_test (add_one,number)) #[2, 3, 4, 5, 6, 7] #2. Using the Map_test function defined by the lambda function, print (Map_test (lambda x:x+1,number)) #[2, 3, 4, 5, 6, 7] #3. Use the map () function to define the print (list ( Map (lambda x:x+1, number))) #[2, 3, 4, 5, 6, 7] #注: Map () The result is a iterator, you need to use the list () function to make it a whole sequence is calculated to return a list

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, and the result is a iterator, which is required by the 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 Functools import reducereduce (function, sequence, initial=none)  #该函数的默认用法

The reduce function, which sequence the elements of a sequence of functions, carries a pair each time (the previous result and the next sequence of elements), successively adds the existing result and the next function to the resulting subsequent result, and finally obtains our sequence as the return value of the final result.

PS1:

 1 number1 = [2,3,4,10] 2 #1. Normal function Definition 3 def chengfa (x, y): 4 return x*y #返回得到两个数相乘的结果 5 def reduce_test (func,seq,init=no     NE): 6 if init is none:7 res = seq.pop (0) #seq删除第一个元素 and gets to delete this element assignment to res 8 else:9 res = init10 For the i in seq:11 res = func (res,i) #循环一次, execute func This function, return RES13 print (Reduce_test (chengfa,number1)) #2 4015 Print (Reduce_test (chengfa,number1,10)) #240017 #如果给了init initial value, which is the result of multiplying the initial value by each element of the list #2. Lambda functions, with reduce The _test () function defines the print (Reduce_test (lambda x,y:x*y,number1,init=3)) #72023 #3. Using reduce (), combined with the Lambda () print (Reduce ( Lambda X,y:x*y, number1)) #24027 28 Gets the list of all the elements, multiplying the result of the NUMBER1 = [2,3,4,10]31 #1. Normal function definition-def chengfa (x, y): retur N x*y #返回得到两个数相乘的结果34 def reduce_test (func,seq,init=none): If init is none:36 res = seq.pop (0) #seq删除第一个元     element, and gets to remove the value assigned to RES37 else:38 res = init39 for i in seq:40 res = func (res,i) #循环一次, perform the Func function 41 return res42 print (Reduce_test (cHengfa,number1) #24044 print (Reduce_test (chengfa,number1,10)) #240046 #如果给了init initial value, which is the result of multiplying from the initial value of each element of the list 48 49 #2. Lambda function, define reduce_test (lambda x,y:x*y,number1,init=3) with the Reduce_test () function #3. Using reduce (), Combine lambda () Functools Import reduce55 print (reduce (lambda x,y:x*y, number1)) #24057 58 get list of all elements, multiply the result

PS2:

Get 1-100 of and

1 print (Reduce (lambda x,y:x+y,range (1,101)))

1.6filter function

The filter () function is used for filtering sequences similar to map (), and filter () also accepts a function and a sequence (an iterative object, which can be a for loop), 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.

Example:

1 AA = [' A ', ' ', ' B ', None, ' C ', '  ] 2 #1. Custom Function Test 3 def not_empty (s): 4     return S and  S.strip () 5 def filter_t EST (func,iter): 6     res = [] 7 for     i in iter:8         i = func (i) 9         if i:10             res.append (i)     return RES12 p Rint (Filter_test (NOT_EMPTY,AA)) #[' A ', ' B ', ' C ']15 #2. Filter built-in function test print (list (filter (NOT_EMPTY,AA))) #[' a ' , ' B ', ' C ']19 #把列表中空字符串, empty 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, 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

Example: Number default sort

1 AA = [11,-10,20,21,30,-40]2 print (sorted (AA))

Note: Receive a key function to implement a custom sort

Example: Sorting by absolute size

1 AA = [11,-10,20,21,30,-40]2 print (sorted (aa,key=abs)) 3 #[-10, 11, 20, 21, 30,-40]

Example: String sorting

1 Print (Sorted ("Hello")) 2 #[' e ', ' h ', ' l ', ' l ', ' O ']3 4 print (sorted (["Hello", "ho", "haha"]) 5 # [' Haha ', ' hello ', ' ho ']

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

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.