Python学习笔记:Python函数式编程
学自廖雪峰巨佬的Python3教程:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014317848428125ae6aa24068b4c50a7e71501ab275d52000
1.我们通过把大段代码拆成函数,通过一层一层的函数调用,就可以把复杂任务分解成简单的任务,这种分解可以称之为面向过程的程序设计。函数就是面向过程的程序设计的基本单元。而函数式编程就是一种抽象程度很高的编程范式,纯粹的函数式编程语言编写的函数没有变量,因此,任意一个函数,只要输入是确定的,输出就是确定的,这种纯函数我们称之为没有副作用。而允许使用变量的程序设计语言,由于函数内部的变量状态不确定,同样的输入,可能得到不同的输出,因此,这种函数是有副作用的。
2.高阶函数
- map()和reduce()
map()接收两个参数,一个是函数,一个是Iterable对象,map将传入的函数依次作用到Iterable对象里的每个元素,并把结果作为新的Iterator返回
>>> def f(x):
... return x * x
...
>>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> list(r)
[1, 4, 9, 16, 25, 36, 49, 64, 81]
由于结果r是一个Iterator,因此需要通过list()函数将整个序列都计算出来并返回一个list()
reduce()把一个函数作用在一个一个序列上,这个函数必须接收两个参数,reduce把结果和序列的下一个元素做累积计算
>>> from functools import reduce
>>> def add(x, y):
... return x + y
...
>>> reduce(add, [1, 3, 5, 7, 9])
25
还可以通过reduce函数写出一个str2int的函数
from functools import reduce
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
def str2int(s):
def fn(x, y):
return x * 10 + y
def char2num(s):
return DIGITS[s]
return reduce(fn, map(char2num, s))
代码如下:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def normalize(name):
return str.upper(str.lower(name)[:1]) + str.lower(name)[1:len(str.lower(name))]
# 测试:
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)
代码如下:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from functools import reduce
def prod(L):
def fn(x, y):
return x * y
return reduce(fn, L)
# 测试
print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
if prod([3, 5, 7, 9]) == 945:
print('测试成功!')
else:
print('测试失败!')
代码如下:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from functools import reduce
def str2float(s):
def char2num(s):
digit = {'0': 0, '1': 1, '2':