Higher-order function 高阶函数
定义:一个函数接受 另一个函数作为参数,这种函数就称之为高阶函数
比如:
def add(x, y, f):
return f(x) + f(y)
当我们调用add(-5, 6, abs)时,参数x,y和f分别接收-5,6和abs,根据函数定义,我们可以推导计算过程为:
x = -5
y = 6
f = abs
f(x) + f(y) ==> abs(-5) + abs(6) ==> 11
return 11
常用的高阶函数:map()
和reduce(),filter,sorted
map()函数:
c=map(lambda x:x*2 ,range(1,4))
这里采用了匿名函数作为一个函数参数传入,后面的每个数据都会作用于传入的函数计算
reduce()函数(需要手动导包: from functools import reduce):
d=reduce(lambda x,y:x+y ,range(1,4))
也是用匿名函数作为参数传入
filter函数:
使用的方法是: result = filter(f(x),listData)
其中f(x)是一个返回boolean类型的函数,函数体的计算作用于后面内容的每一个数据
sorted函数;
源码介绍使用说明:
def sorted(*args, **kwargs): # real signature unknown
"""
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.
"""
pass
意思就是我们使用sorted,传入的参数,可以指定key为一个函数,作为排序的规则,例如:
e=sorted(range(1,6),key=abs,reverse=True) # 按照绝对值,降序排序 f=sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower) # 转小写后排序