Python的化簡函數(shù)reduce()詳解
一、前言
官方解釋如下:
Apply function of two arguments cumulatively to the items of 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). The left argument, x, is the accumulated value and the right argument, y, is the update value from the sequence. If the optional initializer is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty. If initializer is not given and sequence contains only one item, the first item is returned.
格式:
creduce (func, seq[, init()])
reduce()函數(shù)即為化簡函數(shù),它的執(zhí)行過程為:每一次迭代,都將上一次的迭代結(jié)果(注:第一次為init元素,如果沒有指定 init 則為 seq 的第一個元素)與下一個元素一同傳入二元func函數(shù)中去執(zhí)行。在reduce()函數(shù)中,init 是可選的,如果指定,則作為第一次迭代的第一個元素使用,如果沒有指定,就取 seq 中的第一個元素。
二、舉例
有一個序列集合,例如[1,1,2,3,2,3,3,5,6,7,7,6,5,5,5],統(tǒng)計這個集合所有鍵的重復(fù)個數(shù),例如 1 出現(xiàn)了兩次,2 出現(xiàn)了兩次等。
大致的思路就是用字典存儲,元素就是字典的 key,出現(xiàn)的次數(shù)就是字典的 value。
方法依然很多第一種:for 循環(huán)判斷
def statistics(lst):
dic = {}
for k in lst:
if not k in dic:
dic[k] = 1
else:
dic[k] +=1
return dic
lst = [1,1,2,3,2,3,3,5,6,7,7,6,5,5,5]
print(statistics(lst)) 第二種:比較取巧的,先把列表用set方式去重,然后用列表的count方法。
def statistics2(lst):
m = set(lst)
dic = {}
for x in m:
dic[x] = lst.count(x)
return dic
lst = [1,1,2,3,2,3,3,5,6,7,7,6,5,5,5]
print statistics2(lst) 第三種:用reduce方式
def statistics(dic,k):
if not k in dic:
dic[k] = 1
else:
dic[k] +=1
return dic
lst = [1,1,2,3,2,3,3,5,6,7,7,6,5,5,5]
print reduce(statistics,lst,{})
#提供第三個參數(shù),第一次,初始字典為空,作為statistics的第一個參數(shù),然后遍歷lst,作為第二個參數(shù),然后將返回的字典集合作為下一次的第一個參數(shù)
或者
d = {}
d.extend(lst)
print reduce(statistics,d)
#不提供第三個參數(shù),但是要在保證集合的第一個元素是一個字典對象,作為statistics的第一個參數(shù),遍歷集合依次作為第二個參數(shù) 通過上面的例子發(fā)現(xiàn),凡是要對一個集合進行操作的,并且要有一個統(tǒng)計結(jié)果的,能夠用循環(huán)或者遞歸方式解決的問題,一般情況下都可以用reduce方式實現(xiàn)。
到此這篇關(guān)于Python的化簡函數(shù)reduce()詳解的文章就介紹到這了,更多相關(guān)Python的reduce()內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python實現(xiàn)根據(jù)日期獲取當天凌晨時間戳的方法示例
這篇文章主要介紹了Python實現(xiàn)根據(jù)日期獲取當天凌晨時間戳的方法,涉及Python針對日期與時間戳的相關(guān)轉(zhuǎn)換、運算等操作技巧,需要的朋友可以參考下2019-04-04
如何配置關(guān)聯(lián)Python 解釋器 Anaconda的教程(圖解)
這篇文章主要介紹了如何配置關(guān)聯(lián)Python 解釋器 Anaconda的教程,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學(xué)習(xí)火鍋工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-04-04
Python如何實現(xiàn)拆分數(shù)據(jù)集
這篇文章主要介紹了Python如何實現(xiàn)拆分數(shù)據(jù)集問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09

