目录
一、什么是高阶函数
把函数A作为另外一个函数B的参数传入,这样的函数称为高阶函数,高阶函数是函数式编程的体现。函数时编程是指这种高度抽象的编程范式。
二、内置高阶函数
1. abs() --求绝对值
abs(-10) # 10
2.round() -- 求四舍五入
round(1.4) # 1
round(1.5) # 2
高阶函数快速体验:
def testA(a, b, f):
return f(a) + f(b)
result = testA(-10,20,abs)
print(result) # 30
所以,函数式编程大量使用函数,减少了代码的重复,因此程序比较短,开发速度较快。
3. map()
map(func,lst),将传入的函数变量func作用到lst变量的每个元素中,并将结果组成新的迭代器返回。
# 需求:计算一个序列中各个数字的2次方。
testA = [1,2,3,4,5]
def func(x):
return x ** 2
result = map(func,testA)
print(result) # <map object at 0x00000187E1767C10> --Python3返回的是一个迭代器
print(list(result)) # [1, 4, 9, 16, 25] --将迭代器转换成列表形式
4. reduce()
map(func,lst),其中func必须有两个参数。每次func计算的结果继续和序列的下一个元素做累计计算。
注意:reduce()传入的参数func必须接收2歌参数。
# 需求:计算一个序列中各个数字的累加和
import functools
testA = [1,2,3,4,5]
def func(a,b):
return a + b
result = functools.reduce(func, testA)
print(result) # 15
5. filter()
filter(func,lst)函数用于过滤序列,过滤掉不符合条件的元素,返回一个filter对象。如果要转换为列表,可以使用list()来转换。
testA = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def func(x):
return x % 2 == 0
result = filter(func,testA)
print(result) # <filter object at 0x000002DF02407CD0>
print(list(result)) # [2, 4, 6, 8, 10]