Python: map和reduce

可以先google一篇论文:MapReduce: SImplified Data Processing on Large Clusters

1. map

map()函数接收2个参数:一个是函数,一个是可迭代对象iterable。map将传入的函数依次作用到序列的每个元素,并把结果作为新的iterator返回。

由于iterator是惰性的,因此使用map时通常都在最后通过list()函数把整个序列计算出来并返回一个list。

如: r = map(f, [1,2,3])

list(r)

2. reduce

reduce一个函数作用到一个序列[x1, x2, x3, …],这个函数必须接收2个参数,reduce把结果继续和序列的下一个元素做累计计算,效果就是:

reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)

reduce实际上有3个参数,第三个参数是可选的。当使用第三个参数时,reduce会把第三个参数放到第二个参数的前面。表达式如下:

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

posted on 2018-12-25 14:20  freshair_cn  阅读(553)  评论(0编辑  收藏  举报

导航