-
'reduce()' 将一个函数作用在一个序列上( 两个参数 ),把结果和下一个元素做累积计算
reduce() 函数在 python2 是内置函数,从 python3 开始移到了 functools 模块
from functools import reduce
eg.1 简单累乘
list = [1, 2, 3, 4, 5]
def Fun(x, y):
return x * y
>>> reduce(Fun, list)
120
eg.2 性别统计
from functools import reduce
stu =({'name':'Xu Cui', 'age':20, 'sex':'male'},
{'name':'Huangwei Cai', 'age':18, 'sex':'male'},
{'name':'Jingtang Cui', 'age':16, 'sex':'male'},
{'name':'Haixing Lin', 'age':21, 'sex':'female'})
def is_male(acc, list):
if list['sex'] == 'male':
acc += 1
return acc
Count_male = reduce(is_male, stu, 0) # 默认参数 initialize
>>> Count_male
3
eg.3 性别分组
stu =({'name':'Xu Cui', 'age':20, 'sex':'male'},
{'name':'Huangwei Cai', 'age':18, 'sex':'male'},
{'name':'Jingtang Cui', 'age':16, 'sex':'male'},
{'name':'Haixing Lin', 'age':21, 'sex':'female'})
def Group_by_sex(accumulator , value):
accumulator[value['sex']].append(value['name']) # accumulator 方法
return accumulator
Groupe = reduce(Group_by_sex, stu, {'male':[], 'female':[]})
>>> Groupe
{'male': ['Xu Cui', 'Huangwei Cai', 'Jingtang Cui'], 'female': ['Haixing Lin']}