函数式编程之
map
、reduce
1 定义
map(function, iterable, ...)
:返回一个迭代器,该迭代器将函数应用于可迭代的每个项目,产生结果。 如果传递了额外的可迭代参数,则函数必须采用多参数且并行应用于所有可迭代项中的项目。
示例:
>>> list(map(lambda x: x + 2, list(range(10))))
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
functools.reduce(function, iterable[, initializer])
接受两个参数,其将一个函数应用于一个可迭代序列上,从左向右不断将函数累加(cumulatively
)到下一个迭代元素上。其可以等效为;
def reduce(function, iterable, initializer=None):
it = iter(iterable)
if initializer is None:
value = next(it)
else:
value = initializer
for element in it:
value = function(value, element)
return value
示例:
>>> from functools import reduce
# cal ((((0 + 1) + 2) + 3) + 4)
>>> reduce(lambda x, y: x + y, list(range(5)))
10
2 用途
map
经常用于一些简单功能的list
的生成。但是reduce
可以干什么呢?计算诸如:阶乘?看了廖雪峰前辈的博客,喔…原来
int
是这么做的…
具体能做什么,目前我还不清楚。不过先来实现一个int
的字符转换功能吧。
示例:int('123')
to 123
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(strings):
return reduce(lambda x, y: x * 10 + y, map(lambda s: DIGITS[s], strings))
print(str2int('123'))
123
加强版本:str2float
def str2float(s):
digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4,
'5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
i_num_str, f_num_str = s.split('.')
i_num = reduce(lambda x, y: x * 10 + y, map(lambda s: digits[s], i_num_str))
f_num = reduce(lambda x, y: x / 10 + y, map(lambda s: digits[s], f_num_str[: : -1]))
return i_num + f_num / 10.