Python built-in high-order function usage summary

Functions are one of the core content of Python, which can improve code reuse. In order to use the function better, it is necessary to understand some advanced usage of the function.

Python has three built-in higher-order functions: the so-called higher-order function is a function that takes a function as a parameter or returns a function, and these are all higher-order functions.

Three higher-order functions:

1. The map(f, sq) function:

parameter:

f: is a function

sq: is an iterable object, which can be a list, string, etc.

Role: Apply the function f to each element of sq.

Equivalent to: f(x) for x in sq

Explanation: map will not change the original sq, but will return a new iterator object, which can also be said to be a map object.

Example:

When it is converted to a list, it will be output normally.

Two, filter (f, sq) function:

parameter:

f: is a function

sq: is an iterable object, which can be a list, string, etc.

Function: Filter the elements in sq through the function f.

Equivalent to: x for x in sq if f(x) 

Explanation: The filter does not change the original sequence, but returns a new iterator object. filter()The function returns one Iterator, which is a lazy sequence, so to force the filter()completion of the calculation result, you need to use the list()function to get all the results and return the list.

Example:

Three, reduce (f, sq, init) function:

parameter:

f: a function that supports binary operations

sq: an iterable sequence

init: Initialization value

Role: It accepts a function f(x, y) that supports binary operations, which realizes the cumulative calculation of the elements in the sequence sq, and returns a single result.

Example:

Guess you like

Origin blog.csdn.net/dongjinkun/article/details/84483215