高阶函数:一个函数可以作为参数传给另外一个函数,或者一个函数的返回值为另外一个函数(若返回值为该函数本身,则为递归),满足其一则为高阶函数。
#参数为函数
def bar():
print(“in the bar…”)
def foo(func):
func()
print(“in the foo…”)
foo(bar)
#返回值为函数
def bar():
print(“in the bar…”)
def foo(func):
print(“in the foo…”)
return bar
res=foo(bar)
res()
map函数:map函数接收的是两个参数,一个函数,一个序列,其功能是将序列中的值处理再依次返回至列表内。其返回值为一个迭代器现象。
num=[1,2,3,4,5]
def square(x): return x**2#map函数模拟def map_test(func,iter): num_1=[] for i in iter: ret=func(i) # print(ret) num_1.append(ret) return num_1.iter() #将列表转为迭代器对象#map_test函数print(list(map_test(square,num)))#map函数print(list(map(square,num)))#当然map函数的参数1也可以是匿名函数、参数2也可以是字符串
print(list(map_test(lambda x:x.upper(),“amanda”)))print(list(map(lambda x:x.upper(),“amanda”)))
filter函数:filter函数也是接收一个函数和一个序列的高阶函数,其主要功能是过滤。其返回值也是迭代器对象。
names=[“Alex”,“amanda”,“xiaowu”]
#filter函数机制def filter_test(func,iter): names_1=[] for i in iter: if func(i): #传入的func函数其结果必须为bool值,才有意义 names_1.append(i) return names_1#filter_test函数print(filter_test(lambda x:x.islower(),names))#filter函数print(list(filter(lambda x:x.islower(),names)))
reduce函数:reduce函数也是一个参数为函数,一个为可迭代对象的高阶函数,其返回值为一个值而不是迭代器对象,故其常用与叠加、叠乘等。
#reduce函数不是内置函数,而是在模块functools中的函数,故需要导入
from functools import reducenums=[1,2,3,4,5,6]#reduce函数的机制def reduce_test(func,array,ini=None): #ini作为基数 if ini == None: ret =array.pop(0) else: ret=ini for i in array: ret=func(ret,i) return ret#reduce_test函数,叠乘print(reduce_test(lambda x,y:xy,nums,100))#reduce函数,叠乘print(reduce(lambda x,y:xy,nums,100))