from functools import reduse 从模块中导入
reduce函数: 处理一个序列,然后把序列进行合并操作
#**** 问题:求1+2+3+100的和是多少? # 一,原始方法: num_1 = [1,2,3,100] res = 0 for i in num_1: res += i print('结果:',res) 结果: 106 ## 二,固定写死方法: num_1 = [1,2,3,100] def test(array): res = 0 for i in array: res += i return res print('结果:',test(num_1)) 结果: 106 ## 三,灵活写法: 加法变成乘法 num_1 = [1,2,3,100] # def qsum(x,y): # return x+y def test(func,array): res = array.pop(0) for i in array: res += i return res print('结果:',test(lambda x,y:x+y,num_1)) 结果: 106 num_2 = [1,8,3,100] # def mulit(x,y): # return x*y def test(func,array): res = array.pop(0) for i in array: res = func(res,i) return res print('结果:',test(lambda x,y:x*y,num_2)) 结果: 2400
reduce 函数用法:
## 终极版 from functools import reduce num_1 = [1,2,3,100] print(reduce(lambda x,y:x+y,num_1)) print(reduce(lambda x,y:x+y,num_1,60)) 106 166