python中使用reduce函數(shù)實(shí)現(xiàn)加法運(yùn)算,具體方法如下:
reduce:reduce()函數(shù)的作用是對(duì)參數(shù)序列中元素進(jìn)行累積運(yùn)算。
reduce()函數(shù)語(yǔ)法:
reduce(function, iterable[, initializer])
參數(shù):
function:函數(shù),有兩個(gè)參數(shù);
iterable:可迭代對(duì)象;
initializer:可選,初始參數(shù);
reduce()函數(shù)使用方法:
def add(x, y) : # 兩數(shù)相加
return x + y
sum1 = reduce(add, [1,2,3,4,5]) # 計(jì)算列表和
sum2 = reduce(lambda x, y: x+y, [1,2,3,4,5])
print(sum1)
print(sum2)