一、什麼是高階函數
定義
- 函數名作爲參數傳入
- 函數名作爲返回值進行返回
例子
def func2(func1,hello_people):
ret = []
for p in hello_people:
if func1(p):
ret.append(p)
return ret
hello_people = [ "hyjrain","hyjsun","hyjsnow"]
res = func2(lambda n:n.endswith('rain'),hello_people)
print(res)
func2函數就相當於filter函數,func1爲一個傳入的函數,此處傳入的是lamda函數,來判斷字符是否以‘rain’進行結尾
二、filter函數
語法
此函數是將可迭代對象中符合function的對象進行過濾,2.7是輸出列表,3是輸出可迭代對象
filter(function, iterable) #function函數,iterable可迭代對象
簡單例子
def is_odd(n):
return n % 2 == 1
newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(list(newlist))
輸出結果:
[1,3,5,7,9]
二、map函數
語法
調用方式和filter相同
map() 會根據提供的函數對指定序列做映射。
第一個參數 function 以參數序列中的每一個元素調用 function 函數,返回包含每次 function 函數返回值的新列表
2.7返回列表,3.x返回迭代器
示例
# 計算列表各個元素的平方
def square(x) :
return x ** 2
map(square, [1,2,3,4,5])
結果:[1, 4, 9, 16, 25]
# 使用 lambda 匿名函數
map(lambda x: x ** 2, [1, 2, 3, 4, 5])
結果:[1, 4, 9, 16, 25]
# 提供了兩個列表,對相同位置的列表數據進行相加
map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
結果:[3, 7, 11, 15, 19]
三、reduce函數
語法
reduce() 函數會對參數序列中元素進行累積。
函數將一個數據集合(鏈表,元組等)中的所有數據進行下列操作:用傳給 reduce 中的函數 function(有兩個參數)先對集合中的第 1、2 個元素進行操作,得到的結果再與第三個數據用 function 函數運算,最後得到一個結果
調用方式和filter基本相同,只是多了一個init初始值
from functools import reduce #python3中reduce函數被放置於此模塊中
reduce(function, iterable[, initializer]) #function函數,iterable可迭代對象
實現原理
def add(x,y):
return x+y
def func1(func,my_list,init=None):
if init is None:
res = my_list.pop(0)
else:
res = init
for i in my_list:
res = func(res,i)
return res
示例
from functools import reduce
reduce(lambda x,y:x+y, [1,2,3,4,5])
結果:
15