python reduce 函數(shù)使用詳解
reduce() 函數(shù)在 python 2 是內(nèi)置函數(shù), 從python 3 開始移到了 functools 模塊。
官方文檔是這樣介紹的
reduce(...) reduce(function, sequence[, initial]) -> value Apply 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 items of the sequence in the calculation, and serves as a default when the sequence is empty.
從左到右對(duì)一個(gè)序列的項(xiàng)累計(jì)地應(yīng)用有兩個(gè)參數(shù)的函數(shù),以此合并序列到一個(gè)單一值。
例如,reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) 計(jì)算的就是((((1+2)+3)+4)+5)。
如果提供了 initial 參數(shù),計(jì)算時(shí)它將被放在序列的所有項(xiàng)前面,如果序列是空的,它也就是計(jì)算的默認(rèn)結(jié)果值了
嗯, 這個(gè)文檔其實(shí)不好理解。看了還是不懂。 序列 其實(shí)就是python中 tuple list dictionary string 以及其他可迭代物,別的編程語言可能有數(shù)組。
reduce 有 三個(gè)參數(shù)
function | 有兩個(gè)參數(shù)的函數(shù), 必需參數(shù) |
sequence | tuple ,list ,dictionary, string等可迭代物,必需參數(shù) |
initial | 初始值, 可選參數(shù) |
reduce的工作過程是 :在迭代sequence(tuple ,list ,dictionary, string等可迭代物)的過程中,首先把 前兩個(gè)元素傳給 函數(shù)參數(shù),函數(shù)加工后,然后把得到的結(jié)果和第三個(gè)元素作為兩個(gè)參數(shù)傳給函數(shù)參數(shù), 函數(shù)加工后得到的結(jié)果又和第四個(gè)元素作為兩個(gè)參數(shù)傳給函數(shù)參數(shù),依次類推。 如果傳入了 initial 值, 那么首先傳的就不是 sequence 的第一個(gè)和第二個(gè)元素,而是 initial值和 第一個(gè)元素。經(jīng)過這樣的累計(jì)計(jì)算之后合并序列到一個(gè)單一返回值
reduce 代碼舉例,使用REPL演示
>>> def add(x, y): ... return x+y ... >>> from functools import reduce >>> reduce(add, [1,2,3,4]) 10 >>>
上面這段 reduce 代碼,其實(shí)就相當(dāng)于 1 + 2 + 3 + 4 = 10, 如果把加號(hào)改成乘號(hào), 就成了階乘了
當(dāng)然 僅僅是求和的話還有更簡單的方法,如下
>>> sum([1,2,3,4]) 10 >>>
很多教程只講了一個(gè)加法求和,太簡單了,對(duì)新手加深理解還不夠。下面講點(diǎn)更深入的例子
還可以把一個(gè)整數(shù)列表拼成整數(shù),如下
>>> from functools import reduce >>> reduce(lambda x, y: x * 10 + y, [1 , 2, 3, 4, 5]) 12345 >>>
對(duì)一個(gè)復(fù)雜的sequence使用reduce ,看下面代碼,更多的代碼不再使用REPL, 使用編輯器編寫
from functools import reduce scientists =({'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 sum total_age = reduce(reducer, scientists) print(total_age)
這段代碼會(huì)出錯(cuò),看下圖的執(zhí)行過程
所以代碼需要修改
from functools import reduce scientists =({'name':'Alan Turing', 'age':105, 'gender':'male'}, {'name':'Dennis Ritchie', 'age':76, 'gender':'male'}, {'name':'Ada Lovelace', 'age':202, 'gender':'female'}, {'name':'Frances E. Allen', 'age':84, 'gender':'female'}) def reducer(accumulator , value): sum = accumulator + value['age'] return sum total_age = reduce(reducer, scientists, 0) print(total_age)
7, 9 行 紅色部分就是修改 部分。 通過 help(reduce) 查看 文檔,
reduce 有三個(gè)參數(shù), 第三個(gè)參數(shù)是初始值的意思,是可有可無的參數(shù)。
修改之后就不出錯(cuò)了,流程如下
這個(gè)仍然也可以用 sum 來更簡單的完成
sum([x['age'] for x in scientists ])
做點(diǎn)更高級(jí)的事情,按性別分組
from functools import reduce scientists =({'name':'Alan Turing', 'age':105, 'gender':'male'}, {'name':'Dennis Ritchie', 'age':76, 'gender':'male'}, {'name':'Ada Lovelace', 'age':202, 'gender':'female'}, {'name':'Frances E. Allen', 'age':84, 'gender':'female'}) def group_by_gender(accumulator , value): accumulator[value['gender']].append(value['name']) return accumulator grouped = reduce(group_by_gender, scientists, {'male':[], 'female':[]}) print(grouped)
輸出
{'male': ['Alan Turing', 'Dennis Ritchie'], 'female': ['Ada Lovelace', 'Frances E. Allen']}
可以看到,在 reduce 的初始值參數(shù)傳入了一個(gè)dictionary,, 但是這樣寫 key 可能出錯(cuò),還能再進(jìn)一步自動(dòng)化,運(yùn)行時(shí)動(dòng)態(tài)插入key
修改代碼如下
grouped = reduce(group_by_gender, scientists, collections.defaultdict(list))
當(dāng)然 先要 import collections 模塊
這當(dāng)然也能用 pythonic way 去解決
import itertools scientists =({'name':'Alan Turing', 'age':105, 'gender':'male'}, {'name':'Dennis Ritchie', 'age':76, 'gender':'male'}, {'name':'Ada Lovelace', 'age':202, 'gender':'female'}, {'name':'Frances E. Allen', 'age':84, 'gender':'female'}) grouped = {item[0]:list(item[1]) for item in itertools.groupby(scientists, lambda x: x['gender'])} print(grouped)
再來一個(gè)更晦澀難懂的玩法。工作中要與其他人協(xié)作的話,不建議這么用,與上面的例子做同樣的事,看不懂無所謂。
from functools import reduce scientists =({'name':'Alan Turing', 'age':105, 'gender':'male'}, {'name':'Dennis Ritchie', 'age':76, 'gender':'male'}, {'name':'Ada Lovelace', 'age':202, 'gender':'female'}, {'name':'Frances E. Allen', 'age':84, 'gender':'female'}) grouped = reduce(lambda acc, val: {**acc, **{val['gender']: acc[val['gender']]+ [val['name']]}}, scientists, {'male':[], 'female':[]}) print(grouped)
**acc, **{val['gneder']... 這里使用了 dictionary merge syntax , 從 python 3.5 開始引入, 詳情請看 PEP 448 - Additional Unpacking Generalizations 怎么使用可以參考這個(gè) python - How to merge two dictionaries in a single expression? - Stack Overflow
python 社區(qū)推薦寫可讀性好的代碼,有更好的選擇時(shí)不建議用reduce,所以 python 2 中內(nèi)置的reduce 函數(shù) 移到了 functools模塊中
相關(guān)文章
對(duì)sklearn的使用之?dāng)?shù)據(jù)集的拆分與訓(xùn)練詳解(python3.6)
今天小編就為大家分享一篇對(duì)sklearn的使用之?dāng)?shù)據(jù)集的拆分與訓(xùn)練詳解(python3.6),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-12-12Python數(shù)據(jù)操作方法封裝類實(shí)例
這篇文章主要介紹了Python數(shù)據(jù)操作方法封裝類,結(jié)合具體實(shí)例形式分析了Python針對(duì)數(shù)據(jù)庫的連接、執(zhí)行sql語句、刪除、關(guān)閉等操作技巧,需要的朋友可以參考下2017-06-06Python實(shí)現(xiàn)的異步代理爬蟲及代理池
本文主要介紹了Python實(shí)現(xiàn)異步代理爬蟲及代理池的相關(guān)知識(shí),具有很好的參考價(jià)值,下面跟著小編一起來看下吧2017-03-03python圖形繪制奧運(yùn)五環(huán)實(shí)例講解
在本文里我們給大家整理了一篇關(guān)于python圖形繪制奧運(yùn)五環(huán)的實(shí)例內(nèi)容,大家可以跟著學(xué)習(xí)下。2019-09-09Python 中使用 Selenium 單擊網(wǎng)頁按鈕功能
Selenium是一個(gè)用于測試網(wǎng)站的自動(dòng)化測試工具,支持各種瀏覽器包括Chrome、Firefox、Safari等主流界面瀏覽器,同時(shí)也支持phantomJS無界面瀏覽器,本篇文章將介紹如何在 Python 中使用 selenium 單擊網(wǎng)頁上的按鈕,感興趣的朋友一起看看吧2023-11-11解讀MaxPooling1D和GlobalMaxPooling1D的區(qū)別
這篇文章主要介紹了MaxPooling1D和GlobalMaxPooling1D的區(qū)別及說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-12-12python實(shí)現(xiàn)合并多個(gè)list及合并多個(gè)django QuerySet的方法示例
這篇文章主要介紹了python實(shí)現(xiàn)合并多個(gè)list及合并多個(gè)django QuerySet的方法,結(jié)合實(shí)例形式分析了Python使用chain合并多個(gè)list以及合并Django中多個(gè)QuerySet的相關(guān)操作技巧,需要的朋友可以參考下2019-06-06opencv+tesseract實(shí)現(xiàn)驗(yàn)證碼識(shí)別的示例
本文主要介紹了opencv+tesseract實(shí)現(xiàn)驗(yàn)證碼識(shí)別的示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06