Python 大家都该知道的高阶函数
Python 大家都該知道的高階函數
函數式編程現在逐漸被廣大開發(fā)群體接受 ,越來越多的開發(fā)者們開始使用這種優(yōu)雅的開發(fā)模式 ,而我們使用函數式編程最主要的是需要清楚:
- 什么是高階函數(Higher-order Functions)?
- Python 中高階函數有哪些?要怎么用?
高階函數概念
在函數式編程中 ,我們可以將函數當作變量一樣自由使用。一個函數接收另一個函數作為參數 ,這種函數稱之為高階函數。
舉個例子 :
def high_func(f, arr): return [f(x) for x in arr]上面的例子中 , high_func 就是一個高階函數。其中第一個參數 f 是一個函數,第二個參數 arr 是一個數組 ,返回的值是數組中的所有的值在經過 f 函數計算后得到的一個列表 。例如:
from math import factorialdef high_func(f, arr): return [f(x) for x in arr]def square(n): return n ** 2# 使用python自帶數學函數print(high_func(factorial, list(range(10))))# print out: [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]# 使用自定義函數print(high_func(square, list(range(10))))# print out: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]Python 常用高階函數
如同 java、scala 等語言,我們很多常用的高階函數基本都一致 。在開發(fā)中我們經常使用的最基本的高階函數其實就幾個,而我們也可以基于這些函數去進行適當的擴展,那么下面開始介紹幾種常用的高階函數。
map
Make an iterator that computes the function using arguments from each of the iterables. Stops when the shortest iterable is exhausted.
根據提供的函數對指定序列做映射, 并返回映射后的序列,定義:
map(func, *iterables) -->map object- function # 序列中的每個元素需要執(zhí)行的操作, 可以是匿名函數
- *iterables # 一個或多個序列
正如前面所舉的例子 high_func 函數, map 函數是 high_func 函數高階版