Python reduce()函数

时间:2022-04-26
本文章向大家介绍Python reduce()函数,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

MapReduce: Simplified Data Processing on Large Clusters Jeffrey Dean and Sanjay Ghemawat https://research.google.com/archive/mapreduce.html 这篇来自谷歌的论文介绍了map/reduce,摘录如下:

Abstract MapReduce is a programming model and an associated implementation for processing and generating large data sets. Users specify a map function that processes a key/value pair to generate a set of intermediate key/value pairs, and a reduce function that merges all intermediate values associated with the same intermediate key. Many real world tasks are expressible in this model, as shown in the paper. Programs written in this functional style are automatically parallelized and executed on a large cluster of commodity machines. The run-time system takes care of the details of partitioning the input data, scheduling the program’s execution across a set of machines, handling machine failures, and managing the required inter-machine communication. This allows programmers without any experience with parallel and distributed systems to easily utilize the resources of a large distributed system. Our implementation of MapReduce runs on a large cluster of commodity machines and is highly scalable: a typical MapReduce computation processes many terabytes of data on thousands of machines. Programmers find the system easy to use: hundreds of MapReduce programs have been implemented and upwards of one thousand MapReduce jobs are executed on Google’s clusters every day.

简而言之,map()和reduce()是在集群式设备上用来做大规模数据处理的方法,用户定义一个特定的映射,函数将使用该映射对一系列键值对进行处理,直接产生一系列键值对。

Python reduce()函数

redeuce()函数是Python内置高级函数之一,它与之前介绍过的map()函数类似,同样接收一个函数和一个可迭代对象做参数,返回值是一个值,区别在于,reduce()接收的函数必须是2个参数的,它会保留可迭代对象中前两个参数的计算结果作为下一次运算的一个参数,以此类推。 即如果传入的函数是一个2个数求和的函数,reduce()可以实现累加的结果;如果传入的函数是2个数求积的函数,reduce()可以实现阶乘的结果。

形式:

reduce(function, iterator,...)

使用示例:

#!usr/bin/env python3
#_*_ coding: utf-8 _*_
from functools import reduce #Python3 reduce被移到了fectools库里
def square(a, b):
    return a * b
i =  reduce(square, range(1,6))
print(type(i))
print(i)
#结果
<class 'int'>
120

以下两个例子来自廖雪峰的Python教程。

>>> 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