函数式编程现在逐渐被广大开发群体接受,越来越多的开发者们开始使用这种优雅的开发模式,而我们使用函数式编程最主要的是需要清楚:
高阶函数概念在函数式编程中,我们可以将函数当作变量一样自由使用。一个函数接收另一个函数作为参数,这种函数称之为高阶函数。 举个例子: def high_func(f, arr): return [f(x) for x in arr] 上面的例子中, from math import factorial
def high_func(f, arr): return [f(x) for x in arr]
def square(n): return n ** 2
# 使用python自带数学函数 print(high_func(factorial, list(range(10)))) # print out: [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
# 使用自定义函数 print(high_func(square, list(range(10)))) # print out: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] Python 常用高阶函数如同java、scala等语言,我们很多常用的高阶函数基本都一致。在开发中我们经常使用的最基本的高阶函数其实就几个,而我们也可以基于这些函数去进行适当的扩展,那么下面开始介绍几种常用的高阶函数。 map
根据提供的函数对指定序列做映射, 并返回映射后的序列,定义: map(func, *iterables) --> map object
正如前面所举的例子 from math import factorial
def square(n): return n ** 2
# 使用python自带数学函数 facMap = map(factorial, list(range(10))) print(list(facMap)) # print out: [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
# 使用自定义函数 squareMap = map(square, list(range(10))) print(list(squareMap)) # print out: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 可以看到输出了同样的结果,只是与 我们使用匿名函数,也可以传入多个序列,如下 # 使用匿名函数 lamMap = map(lambda x: x * 2, list(range(10))) print(list(lamMap)) # print out: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# 传入多个序列 mutiMap = map(lambda x, y: x+y, list(range(10)), list(range(11, 15))) print(list(mutiMap)) # print out: [11, 13, 15, 17] reduce
大致上来讲, reduce(function, sequence[, initial]) -> value
最后返回函数的计算结果, 和初始参数类型相同 简单举个例子: # 注意,现在 reduce() 函数已经放入到functools包中。 from functools import reduce
result = reduce(lambda x, y: x + y, [1, 2, 3, 4, 5])
print(result) # print out 15 我们可以看到,序列 设定初始值: # 设定初始参数: s = reduce(lambda x, y: x + y, ['1', '2', '3', '4', '5'], "数字 = ")
print(s) # print out:数字 = 12345 需要注意的是:序列数据类型需要和初始参数一致。 filter
filter(function or None, iterable) --> filter object
举个例子: def boy(n): if n % 2 == 0: return True return False
# 自定义函数 filterList = filter(boy, list(range(20)))
print(list(filterList)) # print out: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# 自定义函数 filterList2 = filter(lambda n: n % 2 == 0, list(range(20)))
print(list(filterList2)) # print out: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] 上面我们可以看到,列表中不能被 sorted
def sorted(iterable: Iterable[_T], *, key: Optional[Callable[[_T], Any]] = ..., reverse: bool = ...) -> List[_T]: ...
举个简单例子: list01 = [5, -1, 3, 6, -7, 8, -11, 2] list02 = ['apple', 'pig', 'monkey', 'money']
print(sorted(list01)) # print out: [-11, -7, -1, 2, 3, 5, 6, 8]
print(sorted(list01, key=abs)) # print out: [-1, 2, 3, 5, 6, -7, 8, -11]
# 默认升序 print(sorted(list02)) # print out: ['apple', 'money', 'monkey', 'pig']
# 降序 print(sorted(list02, reverse=True)) # print out: ['pig', 'monkey', 'money', 'apple']
# 匿名函数排序 print(sorted(list02, key=lambda x: len(x), reverse=True)) # print out: ['monkey', 'apple', 'money', 'pig'] 总结以上我们简单的介绍了几个常用的高阶函数的使用,当然还有很多的高阶函数我们可以去研究,比如 代码地址python 高阶函数[1] 参考资料python 高阶函数: https://github.com/JustDoPython/python-100-day/tree/master/day-005 第10天:Python 类与对象
|
|