Higher order functions: functions that accept functions as arguments are higher-order functions
function as a parameter to find the absolute value.
def add (x, Y, f):
return f (x) +f (y)
Add ( -5, 9, ABS)
1). Map () 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.
For example, for list [1, 2, 3, 4, 5, 6, 7, 8, 9], you can use the map () function if you want to square each element of the list:
def f (x):
Return x*x
Print (Map (f, [1, 2, 3, 4, 5]))
Task: Assume that the user entered the English name is not standard, not according to the first letter capitalization, followed by the letter lowercase rules, use the map () function, a list (including a number of nonstandard English names) into a list containing the canonical English name:
Input: [' Adam ', ' LISA ', ' BarT ']
Output: [' Adam ', ' Lisa ', ' Bart ']
def formart_name (name):
Name = Name.lower (). Capitalize ()
return name
Print (Map (formart_name, [' Adam ', ' LISA ', ' BarT ')]
2). The 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 () the incoming function f must receive two parameters, and reduce () calls function f repeatedly on each element of the list and returns the final result value.
The Python3 is placed in the Fucntools module with the first introduction: From Functools import reduce
def f (x, Y):
return x + y
Reduce (f, [1, 3, 5, 7, 9]) sums all the elements of the list #实际上是对
Reduce () can also receive a 3rd optional parameter as the initial value of the calculation. If you set the initial value to 100, the calculation:
Reduce (f, [1, 3, 5, 7, 9],) #结果将变为125
Python-Functional Programming (1)