What is a higher-order function
A higher-order function is a function that can pass a function as a parameter, which is a higher-order function. In other words, if the parameter of a function is a function, then this function is a higher-order function.
Advanced functions can be used by youdef
Keyword customization functions also have built-in higher-order functions that come with Python systems.
Customize a higher-order function
In our example below, one of the parameters of the function senior is a function, so senior is a higher-order function; the parameters of the function tenfold are not functions, so tenfold is just an ordinary function.
# Define higher-order functionsdef senior(func, container): """ Put the data in the container into the function in sequence for calculation. Return the result to the iterator and finally return the iterator. """ lst = list() for i in container: (func(i)) return iter(lst) # Define ordinary function functionsdef tenfold(num): """ Ten times the device Multiply the data by 10 and return the result. """ return num * 10 # Define a listlst = [10, 20666, 'msr'] # Use higher-order functionsit = senior(tenfold, lst) print(list(it)) # [100, 206660, 'msrmsrmsrmsrmsrmsrmsrmsrmsrmsr']
Commonly used built-in higher-order functions
function | Functional |
---|---|
map | Processes data in the iterable object and returns the processed results to the iterator. |
filter | Filter the data in the iterable object and return the filtered data to the iterator. |
reduce | Process the data in the iterable object and return the final result. |
sorted | Sort the data in the iterable object and return the sorted results. |
map function
grammar:map(function, Iterable)
Parameter description
function: function, which can be a custom function or a built-in function;
iterable: iterable object, iterable data. (Container type data and class container type data, range objects, iterators)
Function
Take out the data in the iterable object one by one, then put it in the specified function for processing, put the processed results into the iterator in turn, and finally return this iterator.
Example
Convert the elements in the list to an integer type and return it.
lst = ['1', '2', '3', '4'] """Use the regular writing method""" new_lst = list() for i in lst: new_lst.append(int(i)) print(new_lst) # [1, 2, 3, 4] """Implemented with map function""" it = map(int, lst) new_lst = list(it) print(new_lst) # [1, 2, 3, 4]
Each number in the list is multiplied by 2 in sequence to the power of the subscript index +1. Use custom functions to implement functions.
lst = [1, 2, 3, 4] """Ordinary method, use left shift""" new_lst = list() for i in lst: res = i << i new_lst.append(res) print(new_lst) # [2, 8, 24, 64] """Use map function""" # Define a left-shift function first. The customized function must be a function with parameters and has a return value.def func(num): return num << num new_lst = list(map(func, lst)) print(new_lst) # [2, 8, 24, 64] """Use lambda to simplify""" new_lst = list(map(lambda num: num << num, lst)) print(new_lst) # [2, 8, 24, 64]
filter function
grammar:filter(function, iterable)
The meaning of parameters is the same as that of map functions
Function
Filter is used to filter data, put the data in the iterable object into the function one by one for processing. If the function returns true, the data will be retained; otherwise, it is best to return to the iterator.
Example
Keep even numbers in containers
lst = [11, 2, 3, 34, 4, 4, 55] """General writing""" new_lst = list() for i in lst: if i % 2 == 0: new_lst.append(i) print(new_lst) # [2, 34, 4, 4] """Use filter function""" def func(num): if num % 2 == 0: return True new_lst = list(filter(func, lst)) print(new_lst) # [2, 34, 4, 4] """ filter + lambda """ new_lst = list(filter(lambda num: True if (num % 2 == 0) else False, lst)) print(new_lst) # [2, 34, 4, 4]
Reduce function
grammar:reduce(function, iterable)
The meaning of the parameter is consistent with map and filter.
Function
Calculate the data, place the first two values in the iterable object in the function to make the operation, and obtain the result and the third value in the function to calculate the result, and so on until all the results are calculated, and the final result is returned.
According to the function we should not until the function in reduce needs to be able to receive two parameters.
Example
Use of reduce function needs to be imported from the standard library functools first
Combine the data elements in the list into a number.
from functools import reduce lst = [2, 0, 6, 6, 6] """General Method""" char = str() for i in lst: char += str(i) print(int(char)) # 20666 """Use the reduse function""" def func(x, y): return x * 10 + y res = reduce(func, lst) print(res) # 20666 """ reduce + lambda """ res = reduce((lambda x, y: (x * 10 + y)), lst) print(res) # 20666
sorted function
grammar:sorted(Iterable, key=function, reverse=False)
Parameter description
iterable: iterable object;
key: Specify the function, default is empty;
reverse: The sorting method, default is False, meaning ascending order;
Function
If no function is specified, simply put the data into ASCII to sort; if a function is specified, the data is put into the function for calculation, sort according to the results of the data, and return the new data, without changing the original data.
Note that if a function is specified, the original data is sorted according to the results of the data, rather than the result data after sorting and calculation.
Example
Sort the data in the list.
lst = [1, 23, 34, 5, 6, 342, 12, 12, 2345, -3] """Sort with built-in functions of the list, ascending order by default""" () print(lst) # [-3, 1, 5, 6, 12, 12, 23, 34, 342, 2345] # Sort in descending order(reverse=True) print(lst) # [2345, 342, 34, 23, 12, 12, 6, 5, 1, -3] lst = [1, 23, 34, 5, 6, 342, 12, 12, 2345, -3] """Sorting with sorted""" new_lst = sorted(lst) print(new_lst) # [-3, 1, 5, 6, 12, 12, 23, 34, 342, 2345] print(lst) # [1, 23, 34, 5, 6, 342, 12, 12, 2345, -3]
Another point is that the sorted function can put data into the function for processing and then sort it according to the results.
lst = [1, 23, 34, 5, 6, 342, 12, 12, 2345, -3] """Sort by absolute value""" new_lst = sorted(lst, key=abs) print(new_lst) # [1, -3, 5, 6, 12, 12, 23, 34, 342, 2345] """Sort by the remainder divided by 10""" def func(num): return num % 10 new_lst = sorted(lst, key=func) print(new_lst) # [1, 342, 12, 12, 23, 34, 5, 2345, 6, -3] # You can see that the result of sorting after we specify the function is neither the absolute value of the original data nor the remainder of the original data divided by 10, but the original data is sorted based on these two calculation results.
sort and sorted
Since we have the built-in function sort for the list, why do we still use the sorted function?
- sorted can sort all iterable objects, but sort is just a built-in function for lists and can only sort lists;
- sorted sort returns new data without changing the original data, sort changes the original data;
- sorted can specify functions, sorted according to the calculation results of the function, in a certain way, but sort can only be sorted simply by the size of the number and ASCII.
Summarize
A higher-order function is a function that takes a function as a parameter.
map(Function,Iterable) (take out the elements in the iterable data one by one and put them into the function for calculation. Return the result, and the last data type returned is the iterator)
filter(Function,Iterable) (filters data, puts iterable data into a function for calculation, the result is true and returns the data, otherwise discards it, and the most return data type is the iterator)
reduce(Function,Iterable) (calculate the data, take out the first two elements in the iterable data and put them into the function for calculation. The result is calculated with the next element, and finally returns the final result)
sorted(Iterable,[key=Function],[reverse =Bool(False(default)/True)]) (Sort iterable data, or put iterable data into a function for calculation and sorting the results)
The above is a detailed explanation of the use of high-order functions (map, filter, reduce, sorted) in Python. For more information about high-order functions in Python, please pay attention to my other related articles!