reduce
- 描述
reduce()函数会对参数序列中元素进行累积
- 语法:
reduce(function,iterable[,initializer])
function —— 函数,有两个参数
iterable —— 可迭代对象
initializer —— 可选,初始参数
- 返回值
返回函数计算结果
- 用法
reduce
把一个函数作用一个序列[x1,x2,x3,…]上,这个函数必须接受两个参数,reduce把结果继续和序列的下一个元素做累积计算
from functools import reduce
# python3需要引入functools模块,python2属于内置功能
def f(x,y):
return x + y
a = reduce(f,[1,2,3,4])
# 运算过程等同于f(f(f(1,2),3),4)
print(a)
# 输出结果:10
- 用法案例
把序列[1,3,5,7,9]变换成整数13579
from functools import reduce
def f(x,y):
return x*10 + y
a = reduce(f,[1,3,5,7,9])
print(a)
# 输出结果:13579
配合map(),实现将字符串‘13579’转换成int型13579
from functools import reduce
def f(x,y):
return x*10 + y
def str(s):
d = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
return d[s]
a = reduce(f,map(str,'13579'))
print(a)
# 输出结果:13579