函數式編程如今逐漸被廣大開發羣體接受,愈來愈多的開發者們開始使用這種優雅的開發模式,而咱們使用函數式編程最主要的是須要清楚:java
什麼是高階函數(Higher-order Functions)?python
Python 中高階函數有哪些?要怎麼用?git
在函數式編程中,咱們能夠將函數看成變量同樣自由使用。一個函數接收另外一個函數做爲參數,這種函數稱之爲高階函數。github
舉個例子:編程
def high_func(f, arr): return [f(x) for x in arr]
上面的例子中, high_func
就是一個高階函數。其中第一個參數 f
是一個函數,第二個參數 arr
是一個數組,返回的值是數組中的全部的值在通過 f
函數計算後獲得的一個列表。例如:數組
from math import factorial
def 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]
如同java、scala等語言,咱們不少經常使用的高階函數基本都一致。在開發中咱們常常使用的最基本的高階函數其實就幾個,而咱們也能夠基於這些函數去進行適當的擴展,那麼下面開始介紹幾種經常使用的高階函數。數據結構
Make an iterator that computes the function using arguments from each of the iterables. Stops when the shortest iterable is exhausted.app
根據提供的函數對指定序列作映射, 並返回映射後的序列,定義:ide
map(func, *iterables) --> map object
function
# 序列中的每一個元素須要執行的操做, 能夠是匿名函數函數式編程
*iterables
# 一個或多個序列
正如前面所舉的例子 high_func
函數, map
函數是 high_func
函數高階版,能夠傳入一個函數和多個序列。
from math import factorial
def square(n): return n ** 2
# 使用python自帶數學函數facMap = map(factorial, list(range(10)))print(list(facMap))# print out: [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
# 使用自定義函數squareMap = map(square, list(range(10)))print(list(squareMap))# print out: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
能夠看到輸出了一樣的結果,只是與 python2.X
不用的是, python3.X
中返回 map
類 ,而前者直接返回一個列表。
咱們使用匿名函數,也能夠傳入多個序列,以下
# 使用匿名函數lamMap = map(lambda x: x * 2, list(range(10)))print(list(lamMap))# print out: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# 傳入多個序列mutiMap = map(lambda x, y: x+y, list(range(10)), list(range(11, 15)))print(list(mutiMap))# print out: [11, 13, 15, 17]
Apply a function of two arguments cumulatively to the items of a sequence,from left to right, so as to reduce the sequence to a single value.
大體上來說, reduce
函數須要傳入一個有兩個參數的函數,而後用這個函數從左至右順序遍歷序列並生成結果,定義以下:
reduce(function, sequence[, initial]) -> value
function
# 函數, 序列中的每一個元素須要執行的操做, 能夠是匿名函數
sequence
# 須要執行操做的序列
initial
# 可選,初始參數
最後返回函數的計算結果, 和初始參數類型相同
簡單舉個例子:
# 注意,如今 reduce() 函數已經放入到functools包中。from functools import reduce
result = reduce(lambda x, y: x + y, [1, 2, 3, 4, 5])
print(result)# print out 15
咱們能夠看到,序列 [1, 2, 3, 4, 5]
經過匿名函數進行了累加。
設定初始值:
# 設定初始參數:s = reduce(lambda x, y: x + y, ['1', '2', '3', '4', '5'], "數字 = ")
print(s)# print out:數字 = 12345
須要注意的是:序列數據類型須要和初始參數一致。
Return an iterator yielding those items of iterable for which function(item) is true. If function is None, return the items that are true.
filter()
函數用來過濾序列中不符合條件的值,返回一個迭代器,該迭代器生成那些函數(項)爲true的iterable項。若是函數爲None,則返回爲true的項。定義以下:
filter(function or None, iterable) --> filter object
function or None
# 過濾操做執行的函數
iterable
# 須要過濾的序列
舉個例子:
def boy(n): if n % 2 == 0: return True return False
# 自定義函數filterList = filter(boy, list(range(20)))
print(list(filterList))# print out: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# 自定義函數filterList2 = filter(lambda n: n % 2 == 0, list(range(20)))
print(list(filterList2))# print out: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
上面咱們能夠看到,列表中不能被 2
整除的數據都被排除了。
Return a new list containing all items from the iterable in ascending order.
A custom key function can be supplied to customize the sort order, and the reverse flag can be set to request the result in descending order.
sorted
函數默認將序列升序排列後返回一個新的 list,還能夠自定義鍵函數來進行排序,也能夠設置 reverse
參數肯定是升序仍是降序,若是 reverse = True
則爲降序。函數定義以下:
def sorted(iterable: Iterable[_T], *, key: Optional[Callable[[_T], Any]] = ..., reverse: bool = ...) -> List[_T]: ...
iterable
# 序列
key
# 能夠用來計算的排序函數。
reverse
# 排序規則,reverse = True降序,reverse = False 升序(默認)。
舉個簡單例子:
list01 = [5, -1, 3, 6, -7, 8, -11, 2]list02 = ['apple', 'pig', 'monkey', 'money']
print(sorted(list01))# print out: [-11, -7, -1, 2, 3, 5, 6, 8]
print(sorted(list01, key=abs))# print out: [-1, 2, 3, 5, 6, -7, 8, -11]
# 默認升序print(sorted(list02))# print out: ['apple', 'money', 'monkey', 'pig']
# 降序print(sorted(list02, reverse=True))# print out: ['pig', 'monkey', 'money', 'apple']
# 匿名函數排序print(sorted(list02, key=lambda x: len(x), reverse=True))# print out: ['monkey', 'apple', 'money', 'pig']
以上咱們簡單的介紹了幾個經常使用的高階函數的使用,固然還有不少的高階函數咱們能夠去研究,好比 zip
函數等,但願此節的介紹對你們有所幫助。
python 高階函數[1]
[1]
python 高階函數: https://github.com/JustDoPython/python-100-day/tree/master/day-005
系列文章
第11天:Python 字典