一、基本概念
所谓高阶函数,即一个函数的参数可接收另一个函数或者一个函数的返回值为另一个函数,满足两者之一就称为高阶函数。
二、自定义高阶函数
#参数为函数
def hi(a):
print('There is a{}.'.format(a))
return a
def eat(b, c):
b(c)
print('The{}is eating.'.format(c))
#返回值为函数
def eat2(a):
print('The{}is eating.'.format(a))
def hi2(b):
print('There is a{}.'.format(b))
return eat2
调用:eat(hi, ‘cat’)
输出:
There is a cat.
The cat is eating.
调用:
ret = hi2(‘cat’)
ret(‘cat’)
输出:
There is a cat.
The cat is eating.
三、内置高阶函数
1.map函数
功能:map函数接收的是两个参数,一个是函数,一个是序列,其功能是将序列中的值传至函数处理再依次接收函数返回值至列表内,在python3中,map函数为一个迭代器对象
举例:
ls = [1, 2, 3]
ls2 = list(map(lambda x: x * 2, ls))
print(ls2)
输出:[2, 4, 6]
2.reduce函数
功能:reduce函数会用传给它的函数function(有两个参数)先对序列中的第 1、2 个元素进行操作,得到的结果再与第三个数据用function函数运算,最后得到一个结果
举例:
from functools import reduce
ls = [1, 2 ,3]
ls2 = reduce(lambda x, y:x * 10 + y, ls)
print(ls2)
输出:123
3.filter函数
功能:根据传给它的函数对序列中的元素进行判断,为True则添加进列表中,最后返回一个可迭代对象
举例:
ls = [1, 2, 3, 4, 5]
ls2 = list(filter(lambda x: x % 2 == 0), ls)
print(ls2)
输出:[2, 4]