按照惯例,在学习reduce函数之前在交互模式下看下reduce的文档(万一有坑,可以在开始的时候给填上)
python2 >>>
Help on built-in function reduce in module __builtin__:
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.
1. apply a function of two arguments 必须是两个参数的函数作为第一个参数
2. If initial is present, it is placed before the items of the sequence in the calculation 第三个参数作用是第一次循环的时候的传递给作用函数func(x,y)中的x参数
python3 >>>
与python2作用上没有太大的区别
python3将reduce函数从内置函数中移动到了functools模块中了
实例:
1. 计算1~5的和以及10为初始X
#!/usr/bin/env python2.7
# -*- coding=utf-8 -*-
reduce(lambda x, y:x + y,[1,2,3,4,5],10)
#!/usr/bin/env python3.0
# -*- coding=utf-8 -*-
from functools import reduce
reduce(lambda x, y:x + y,[1,2,3,4,5],10)
2. 统计<这段代码从https://blog.csdn.net/taxueguilai1992/article/details/50382619/ 借鉴过来的,感觉作为例子不错>
#!/usr/bin/env python2.7
# -*- coding=utf-8 -*-
str="an apple a banana three apple a desk"
list=str.split(' ')
def fun(x, y):
if y in x:
x[y]=x[y]+1
else:
x[y]=1
return x
result=reduce(fun, list,{})
>>>{'a': 2, 'apple': 2, 'three': 1, 'an': 1, 'desk': 1, 'banana': 1}