Python Reduce
- 累加,累乘,每次写起来是不是很烦? 来,看个现成的。
x = [1,2,3,4,5]
def reduce_test(func,array):
if len(array) == 0:
return None
if len(array) == 1:
return array[0]
res = array[0]
for i in array[1:]:
res = func(res,i)
return res
print(reduce_text(lambda x,y:x*y,x))
Result: 120
上面我们自定义了一个函数,其实python中直接有包可以用
from functools import reduce
x= [1,2,3,4,5]
print(reduce(lambda x,y:x*y,x))
Result: 120