reduce() 函數(shù)在 python 2 是內(nèi)置函數(shù), 從python 3 開始移到了 functools 模塊。
官方文檔是這樣介紹的
reduce(...)reduce(function, sequence[, initial]) -> valueApply a function of two arguments cumulatively to the items of a sequence,from left to right, so as to reduce the sequence to a single value.For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates((((1+2)+3)+4)+5). If initial is present, it is placed before the itemsof the sequence in the calculation, and serves as a default when thesequence is empty.從左到右對一個序列的項累計地應(yīng)用有兩個參數(shù)的函數(shù),以此合并序列到一個單一值。例如,reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) 計算的就是((((1+2)+3)+4)+5)。如果提供了 initial 參數(shù),計算時它將被放在序列的所有項前面,如果序列是空的,它也就是計算的默認(rèn)結(jié)果值了
嗯, 這個文檔其實不好理解。看了還是不懂。 序列 其實就是python中 tuple list dictionary string 以及其他可迭代物,別的編程語言可能有數(shù)組。
reduce 有 三個參數(shù)
function 有兩個參數(shù)的函數(shù), 必需參數(shù)
sequence tuple ,list ,dictionary, string等可迭代物,必需參數(shù)
initial 初始值, 可選參數(shù)
reduce的工作過程是 :在迭代sequence(tuple ,list ,dictionary, string等可迭代物)的過程中,首先把 前兩個元素傳給 函數(shù)參數(shù),函數(shù)加工后,然后把得到的結(jié)果和第三個元素作為兩個參數(shù)傳給函數(shù)參數(shù), 函數(shù)加工后得到的結(jié)果又和第四個元素作為兩個參數(shù)傳給函數(shù)參數(shù),依次類推。 如果傳入了 initial 值, 那么首先傳的就不是 sequence 的第一個和第二個元素,而是 initial值和 第一個元素。經(jīng)過這樣的累計計算之后合并序列到一個單一返回值
reduce 代碼舉例,使用REPL演示
>>> def add(x, y):... return x+y...>>> from functools import reduce>>> reduce(add, [1,2,3,4])>>>
上面這段 reduce 代碼,其實就相當(dāng)于 1 + 2 + 3 + 4 = 10, 如果把加號改成乘號, 就成了階乘了
當(dāng)然 僅僅是求和的話還有更簡單的方法,如下
>>> sum([1,2,3,4])10>>>
很多教程只講了一個加法求和,太簡單了,對新手加深理解還不夠。下面講點更深入的例子
還可以把一個整數(shù)列表拼成整數(shù),如下
>>> from functools import reduce>>> reduce(lambda x, y: x * 10 + y, [1 , 2, 3, 4, 5])12345>>>
對一個復(fù)雜的sequence使用reduce ,看下面代碼,更多的代碼不再使用REPL, 使用編輯器編寫
from functools import reducescientists =({'name':'Alan Turing', 'age':105}, {'name':'Dennis Ritchie', 'age':76}, {'name':'John von Neumann', 'age':114}, {'name':'Guido van Rossum', 'age':61})def reducer(accumulator , value): sum = accumulator['age'] + value['age'] return sumtotal_age = reduce(reducer, scientists)print(total_age)
新聞熱點
疑難解答