# 弄明白python reduce 函数

reduce() 函数在 python 2 是内置函数， 从python 3 开始移到了 functools 模块。

reduce(…)
reduce(function, sequence[, initial]) -> value

Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.

reduce 有 三个参数

function 有两个参数的函数， 必需参数
sequence tuple ，list ，dictionary， string等可迭代物，必需参数
initial 初始值， 可选参数
reduce的工作过程是 ：在迭代sequence(tuple ，list ，dictionary， string等可迭代物)的过程中，首先把 前两个元素传给 函数参数，函数加工后，然后把得到的结果和第三个元素作为两个参数传给函数参数， 函数加工后得到的结果又和第四个元素作为两个参数传给函数参数，依次类推。 如果传入了 initial 值， 那么首先传的就不是 sequence 的第一个和第二个元素，而是 initial值和 第一个元素。经过这样的累计计算之后合并序列到一个单一返回值

reduce 代码举例，使用REPL演示

def add(x, y):
… return x+y

from functools import reduce
reduce(add, [1,2,3,4])
10

sum([1,2,3,4])
10

from functools import reduce
reduce(lambda x, y: x * 10 + y, [1 , 2, 3, 4, 5])
12345

1 from functools import reduce
2 scientists =({‘name’:’Alan Turing’, ‘age’:105},
3 {‘name’:’Dennis Ritchie’, ‘age’:76},
4 {‘name’:’John von Neumann’, ‘age’:114},
5 {‘name’:’Guido van Rossum’, ‘age’:61})
6 def reducer(accumulator , value):
7 sum = accumulator[‘age’] + value[‘age’]
8 return sum
9 total_age = reduce(reducer, scientists)
10 print(total_age)

1 from functools import reduce
2 scientists =({‘name’:’Alan Turing’, ‘age’:105, ‘gender’:’male’},
3 {‘name’:’Dennis Ritchie’, ‘age’:76, ‘gender’:’male’},
4 {‘name’:’Ada Lovelace’, ‘age’:202, ‘gender’:’female’},
5 {‘name’:’Frances E. Allen’, ‘age’:84, ‘gender’:’female’})
6 def reducer(accumulator , value):
7 sum = accumulator + value[‘age’]
8 return sum
9 total_age = reduce(reducer, scientists, 0)
10 print(total_age)

7， 9 行 红色部分就是修改 部分。 通过 help(reduce) 查看 文档，
reduce 有三个参数， 第三个参数是初始值的意思，是可有可无的参数。

sum([x[‘age’] for x in scientists ])

from functools import reduce
scientists =({‘name’:’Alan Turing’, ‘age’:105, ‘gender’:’male’},
{‘name’:’Dennis Ritchie’, ‘age’:76, ‘gender’:’male’},
{‘name’:’Ada Lovelace’, ‘age’:202, ‘gender’:’female’},
{‘name’:’Frances E. Allen’, ‘age’:84, ‘gender’:’female’})
def group_by_gender(accumulator , value):
accumulator[value[‘gender’]].append(value[‘name’])
return accumulator
grouped = reduce(group_by_gender, scientists, {‘male’:[], ‘female’:[]})
print(grouped)

{‘male’: [‘Alan Turing’, ‘Dennis Ritchie’], ‘female’: [‘Ada Lovelace’, ‘Frances E. Allen’]}

grouped = reduce(group_by_gender, scientists, collections.defaultdict(list))

import itertools
scientists =({‘name’:’Alan Turing’, ‘age’:105, ‘gender’:’male’},
{‘name’:’Dennis Ritchie’, ‘age’:76, ‘gender’:’male’},
{‘name’:’Ada Lovelace’, ‘age’:202, ‘gender’:’female’},
{‘name’:’Frances E. Allen’, ‘age’:84, ‘gender’:’female’})
grouped = {item[0]:list(item[1])
for item in itertools.groupby(scientists, lambda x: x[‘gender’])}
print(grouped)

from functools import reduce
scientists =({‘name’:’Alan Turing’, ‘age’:105, ‘gender’:’male’},
{‘name’:’Dennis Ritchie’, ‘age’:76, ‘gender’:’male’},
{‘name’:’Ada Lovelace’, ‘age’:202, ‘gender’:’female’},
{‘name’:’Frances E. Allen’, ‘age’:84, ‘gender’:’female’})
grouped = reduce(lambda acc, val: {acc, {val[‘gender’]: acc[val[‘gender’]]+ [val[‘name’]]}}, scientists, {‘male’:[], ‘female’:[]})
print(grouped)

acc， {val[‘gneder’]… 这里使用了 dictionary merge syntax , 从 python 3.5 开始引入， 详情请看 PEP 448 - Additional Unpacking Generalizations 怎么使用可以参考这个 python - How to merge two dictionaries in a single expression? - Stack Overflow

python 社区推荐写可读性好的代码，有更好的选择时不建议用reduce，所以 python 2 中内置的reduce 函数 移到了 functools模块中

#### 每个新手都要搞懂弄明白的

2008-10-05 10:05:00

#### 我们什么东西都要搞明白吗

2011-11-14 10:00:39

#### 代理模式与装饰模式的理解

2016-07-12 23:56:25

#### Python reduce()函数的用法

2015-07-20 23:04:22

#### python里使用reduce()函数

2017-09-29 08:31:09

#### python中reduce函数的用法

2015-12-22 22:03:53

#### python map(),reduce()函数的使用

2016-06-05 17:48:10

#### Python3.4中filter函数，map函数和reduce函数

2015-03-08 22:28:09

#### Python笔记|Python3中没有reduce函数的原因

2018-02-07 18:07:11

#### Python reduce()求积

2016-04-21 15:07:23