寫 Python 代碼不可不知的函數(shù)式編程技術(shù)
??????關(guān)注我,和老表一起學(xué)Python、云服務(wù)器
來源 : 機器之心
本文對 Python 中的函數(shù)式編程技術(shù)進(jìn)行了簡單的入門介紹。

def?foo():
???print("foo")bar?=?foo
bar()
#will?print?"foo"?to?the?consoleclass?Greeter:
???def?__init__(self,?greeting):
??????self.greeting?=?greeting
???def?__call__(self,?name):
??????return?self.greeting?+?"?"?+?namemorning?=?Greeter("good?morning")?#creates?the?callable?object
morning("john")?#?calling?the?object
#prints?"good?morning?john"?to?the?consolecallable(morning)?#true
callable(145)?#false.?int?is?not?callable.?#?store?in?dictionary
mapping?=?{
???0?:?foo,
???1?:?bar
}
x?=?input()?#get?integer?value?from?user
mapping[x]()?#call?the?func?returned?by?dictionary?access「高階函數(shù)允許我們對動作執(zhí)行抽象,而不只是抽象數(shù)值。」
def?iterate(list_of_items):
????for?item?in?list_of_items:
????????print(item)
看起來很酷吧,但這只不過是一級抽象而已。如果我們想在對列表執(zhí)行迭代時進(jìn)行打印以外的其他操作要怎么做呢?
def?iterate_custom(list_of_items,?custom_func):
???for?item?in?list_of_items:
????????custom_func(item)def?add(x,?y):
????return?x?+?y
def?sub(x,?y):
????return?x?-?y
def?mult(x,?y):
????return?x?*?y
def?calculator(opcode):
????if?opcode?==?1:
???????return?add
????elif?opcode?==?2:
???????return?sub
????else:
???????return?mult?
my_calc?=?calculator(2)?#my?calc?is?a?subtractor
my_calc(5,?4)?#returns?5?-?4?=?1?
my_calc?=?calculator(9)?#my?calc?is?now?a?multiplier
my_calc(5,?4)?#returns?5?x?4?=?20.?
嵌套函數(shù)
def?fib(n):
????def?fib_helper(fk1,?fk,?k):
????????if?n?==?k:
???????????return?fk
????????else:
???????????return?fib_helper(fk,?fk1+fk,?k+1)
????if?n?<=?1:
???????return?n
????else:
???????return?fib_helper(0,?1,?1)
將該計算從函數(shù)主體移到函數(shù)參數(shù),這具備非常強大的力量。因為它減少了遞歸方法中可能出現(xiàn)的冗余計算。
mult?=?lambda?x,?y:?x?*?y
mult(1,?2)?#returns?2
該 mult 函數(shù)的行為與使用傳統(tǒng) def 關(guān)鍵字定義函數(shù)的行為相同。
(lambda?x,?y:?x?*?y)(9,?10)?#returns?90import?collections
pre_fill?=?collections.defaultdict(lambda:?(0,?0))
#all?dictionary?keys?and?values?are?set?to?0def?multiply_by_four(x):
????return?x?*?4
scores?=?[3,?6,?8,?3,?5,?7]
modified_scores?=?list(map(multiply_by_four,?scores))
#modified?scores?is?now?[12,?24,?32,?12,?20,?28]
在 Python 3 中,map 函數(shù)返回的 map 對象可被類型轉(zhuǎn)換為 list,以方便使用。現(xiàn)在,我們無需顯式地定義 multiply_by_four 函數(shù),而是定義 lambda 表達(dá)式:
modified_scores?=?list(map(lambda?x:?4?*?x,?scores))even_scores?=?list(filter(lambda?x:?True?if?(x?%?2?==?0)?else?False,?scores))
#even_scores?=?[6,?8]sum_scores?=?reduce((lambda?x,?y:?x?+?y),?scores)
#sum_scores?=?32Best Practices for Using Functional Programming in Python:https://kite.com/blog/python/functional-programming/
Functional Programming Tutorials and Notes:https://www.hackerearth.com/zh/practice/python/functional-programming/functional-programming-1/tutorial/
原文鏈接:https://medium.com/better-programming/introduction-to-functional-programming-in-python-3d26cd9cbfd7
老表每周一贈書
圖書介紹:《利用Python進(jìn)行數(shù)據(jù)分析》本書由Python pandas項目創(chuàng)始人Wes McKinney親筆撰寫,詳細(xì)介紹利用Python進(jìn)行操作、處理、清洗和規(guī)整數(shù)據(jù)等方面的具體細(xì)節(jié)和基本要點。第2版針對Python 3.6進(jìn)行全面修訂和更新,涵蓋新版的pandas、NumPy、IPython和Jupyter,并增加大量實際案例,可以幫助你高效解決一系列數(shù)據(jù)分析問題。 點擊下方卡片直接購買學(xué)習(xí)
贈書規(guī)則:給本文點贊+周一隨意留言,留言點贊top1可以直接獲得贈書一本,另外我將隨機抽取一位讀者朋友贈書一本。
額外加成:本次留言點贊top10讀者,在參與下次贈書活動時可以獲得20%點贊額加成,比如你本次留言點贊量為20個,如果下次點贊活動你也參與了,點贊量為24,那么計算排名時你的點贊量為:24+20*20% = 28個(額外加成量上限為10個)。
老表學(xué)習(xí)交流群專屬福利:
掃下方二維碼,加我好友,通過后直接回復(fù):進(jìn)群,即可獲取入群方法(僅限有一點Python基礎(chǔ)的讀者,一點基礎(chǔ)沒有的,建議上B站看視頻學(xué)習(xí),推薦小甲魚Python)。
今天20:00將在群內(nèi)隨機抽選一位讀者贈送《深入淺出Pandas:利用Python進(jìn)行數(shù)據(jù)處理與分析》。
【推薦閱讀】用Pandas對數(shù)據(jù)進(jìn)行復(fù)雜查詢,7步教你隨心所欲地取用數(shù)據(jù)
掃碼即可加我微信
老表朋友圈經(jīng)常有贈書/紅包福利活動
【??注】同一讀者同一月內(nèi)最多只能獲得一本贈書;必須在收到贈書后學(xué)習(xí)完圖書內(nèi)容/投稿學(xué)習(xí)筆記一篇后才能獲得下一本贈書。
--END--
近期優(yōu)質(zhì)文章:
學(xué)習(xí)更多: 整理了我開始分享學(xué)習(xí)筆記到現(xiàn)在超過250篇優(yōu)質(zhì)文章,涵蓋數(shù)據(jù)分析、爬蟲、機器學(xué)習(xí)等方面,別再說不知道該從哪開始,實戰(zhàn)哪里找了 “點贊”就是對博主最大的支持?

