Beson's Blog
阿新 • • 發佈:2018-12-14
- 定義 高階函式:能夠接收函式作為引數的函式。 函式可以賦值給變數,函式的引數可以接收變數,因此一個函式可以接收另一個函式作為引數,這種函式就稱為高階函式。
- DEMO
def add(x,y,f): #f式一個函式引數
return f(x)+f(y)
add(-1,2 abs) #結果等於1
- Python 內建的高階函式
- map/reduce map()定義: Python 內建的高階函式,它接收一個函式 f 和一個 list,並通過把函式 f 依次作用在 list 的每個元素上,得到一個新的 list 並返回。 reduce()定義:它接收一個函式 f (這個函式必須能夠接收兩個引數)和一個 list,函式會依次作用在list的每個元素,並且reduce會將每次作用在元素的值與下一個元素作用在函式的值進行累加。reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)。
#map() DEMO
def f(x):
return 2*x
result=map(f,[1,2,3,4])
print(result)#列印的結果為[2,4,6,8]
#reduce() DEMO
def add(x,y):
return x+y
result = reduce(add,[1,2,3,4])
print(result) #列印的結果為10(1+2+3+4)
- filter 定義:用於過濾掉不符合條件的序列,該函式接收兩個引數,一個是函式,一個是序列,序列的每個元素傳遞給函式進行判斷,函式返回true或false,最後將true的元素重新組成一個新的序列。
#DEMO def is_odd(x): return x%2==1 result=filter(is_odd,[1,2,3,4,5,6,7]) print(result) #[1,3,5,7]
- sorted 定義:sorted()也是一個高階函式,它可以接收一個比較函式來實現自定義的排序。
#DEMO
def cmp(x,y):
if x>y:
return -1
if x<y:
return 1
return 0
result=sorted([1,2,3,45,0],cmp)
print(result) #[45, 3, 2, 1, 0]