python reduce 函数使用
reduce(…)
reduce(function, sequence[, initial]) -> value
从左到右对一个序列的项累计地应用有两个参数的函数,以此合并序列到一个单一值。
例如,reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) 计算的就是((((1+2)+3)+4)+5)。
如果提供了 initial 参数,计算时它将被放在序列的所有项前面,如果序列是空的,它也就是计算的默认结果值。
#简单的列表
def add(x,y):
return x+y
from functools import reduce
reduce(add,[1,2,3,4,5])
10
#字典
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 reducer(accumulator , value):
sum = accumulator + value['age']
return sum
total_age = reduce(reducer, scientists, 0)
print(total_age)
467
#简单实现
#sum([x['age'] for x in scientists ])
而accumulate函数返回是一个可迭代对象,可以用在for里面,而不是最后的累加结果。
accumulate函数的功能是对传进来的iterable对象逐个进行某个操作(默认是累加,如果传了某个fun就是应用此fun。比如iterable=[1,2,3,4] 默认会先累加iterable 0~0(1), 然后0~1(1+2),最后0~3(1+2+3)
结果会是[1,3,6,10]
>>> a=[1,2,3,4,5]
>>> b=accumulate(a) #默认是累加
>>> b #这里返回的是一个可迭代对象
<itertools.accumulate object at 0x7f3e5c2f4e48>
>>> list(b) #如果我们想要的是直接的结果需要强制转化类型
[1, 3, 6, 10, 15]
>>>
参考自:弄明白python reduce 函数 作者:Panda Fang
作者:奋力翻身的咸鱼=_=