2018-08-11
reduce用法:
reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算
效果是:reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
求和序列采用reduce:
from functools import reduce
>>> def add(x,y):
... return x + y
...
>>> reduce(add,[1,3,5,7,9])
25
如果要把序列[1, 3, 5, 7, 9]变换成整数13579
from functools import reduce
>>> def fn(x,y):
... return x * 10 + y
...
>>> reduce(fn,[1,3,5,7,9])
13579
考虑到字符串str也是一个序列,配合map(),我们就可以写出把str转换为int的函数:
from functools import reduce
>>> def fn(x,y):
... return x * 10 + y
...
>>> def char2num(s):
... digits = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}
... return digits[s]
...
>>> reduce(fn,map(char2num,'13579'))
13579
整理成一个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))
lambda函数进行简化:
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 char2num(s):
return DIGITS[s]
def str2int(s):
return reduce(lambda x, y: x * 10 + y, map(char2num, s))
lambda函数的定义:
b = lambda a:a+1
>>> print(b(3))
4
>>>
>>>
>>> def fun(a):
... return a+1
...
>>> print(fun(3))
4