场景模拟:
序列元素在原有基础上加1
常规方法
简单但扩展性查
1 num1 = [1,2,3,4,5,6,7,8,9,100] 2 res = 0 3 for i in num1: 4 res += i 5 print(res)
函数方法
扩展性好,代码多
1 num1 = [1,2,3,4,5,6,7,8,9,100] 2 def reduce_test(array): 3 res = 0 4 for i in array: 5 res += i 6 return res 7 print(reduce_test(num1))
reduce 函数
场景模拟 :序列内的所有元素相乘
内部原理,参数两个,方法以及预处理参数
1 num1 = [1,2,3,4,5,6,7,8,9,100] 2 # def multi(x,y): 3 # return x*y 4 # lambda x,y:x*y 5 def reduce_test(func,array): 6 res = array.pop(0) 7 for i in array: 8 res = func(res,i) 9 return res 10 print(reduce_test(lambda x,y:x*y,num1))
reduce函数支持初始值
场景模拟 :序列内的所有元素相乘,并附加一个初始值一起相乘操作
代入初始值后的原理
1 num1 = [1,2,3,4,5,6,7,8,9,100] 2 # def multi(x,y): # 依旧是运算方法简单的话可以用匿名函数替换 3 # return x*y 4 # lambda x,y:x*y 5 def reduce_test(func,array,init=None): # 在参数中加入了初始值 6 if init is None: 7 res = array.pop(0) 8 else: 9 res=init 10 for i in array: 11 res = func(res,i) 12 return res 13 print(reduce_test(lambda x,y:x*y,num1,10000))
reduce 函数
在Python3中,reduce()函数已经被从全局名字空间里移除了,
放置在fucntools模块里,通过引入functools模块来调用
1 from functools import reduce 2 num1 = [1,2,3,4,5,6,7,8,9,100] 3 print(reduce(lambda x,y:x*y,num1,10))