函數式程式設計是使用一系列函數去解決問題,按照一般程式設計思維,面對問題時我們的思考方式是“怎麼幹”,而函數函數式程式設計的思考方式是我要“幹嘛”。 至於函數式程式設計的特性暫不總結,我們直接拿例子來體會什麼是函數式程式設計。
lambda表達式(匿名函數):
普通函數與匿名函數的定義方式:
普通函數def add( a,b):
return a + bprint add(2,3) #匿名函数add = lambda a,b : a + bprint add(2,3)#========输出===========5 5
匿名函數的命名規則,用lamdba 關鍵字標識,冒號(:)左側表示函數接收的參數(a, b) ,冒號(:)右邊表示函數的回傳值(a+b)。
因為lamdba在創建時不需要命名,所以,叫匿名函數^_^
Map函數:
##計算字串長度
#
abc = ['com','fnng','cnblogs']for i in range(len(abc)): print len(abc[i])#========输出===========347定義abc字串數組,計算abc長度然後循環輸出數組中每個字串的長度。 來看看map()函數是如何來實現這個過程的。
abc_len = map(len,['hao','fnng','cnblogs'])print abc_len#========输出===========[3, 4, 7]雖然,輸出的結果中是一樣的,但它們的形式不同,第一種是單純的數值了,map()函數的輸出仍然保持了數組的格式。 大小寫轉換;python提供有了,upper() 和 lower() 來轉換大小寫。
print ss.upper() #轉換成大寫print ss.lower() #轉換成小寫# ========輸出===========HELLO WORLD!
hello world!
def to_lower(item): return item.lower()name = map(to_lower,['cOm','FNng','cnBLoGs'])print name#========输出===========['com', 'fnng', 'cnblogs']這個範例中我們可以看到,我們寫義了一個函數toUpper,這個函數沒有改變傳進來的值,只是把傳進來的值做個簡單的操作,然後回傳。然後,我們把其用在map函數中,就可以很清楚地描述出我們想要做什麼。
#
abc = ['cOm','FNng','cnBLoGs']lowname = []for i in range(len(abc)): lowname.append(abc[i].lower())print lowname#========输出===========['hao', 'fnng', 'cnblogs']map()函數加上lambda表達式(匿名函數)可以實現更強大的功能。 #求平方#0*0,1*1,2*2,3*3,....8*8squares = map(lambda x : x*x ,range(9))print squares #========輸出===========[0, 1, 4, 9, 16, 25, 36, 49, 64]Reduce函數:
def add(a,b): return a+b add = reduce(add,[2,3,4])print add#========输出===========9 对于Reduce函数每次是需要对两个数据进行处理的,首选取2 和3 ,通过add函数相加之后得到5,接着拿5和4 ,再由add函数处理,最终得到9 。在前面map函數範例中我們可以看到,map函數是每次只對一個資料進行處理。 然後,我們發現透過Reduce函數加lambda表達式實現階乘是如何簡單:##5階乘#5! =1*2*3*4*5print reduce(lambda x,y: x*y, range(1,6))#========輸出===========120 Python中的除了map和reduce外,還有一些別的如filter, find, all, any的函數做輔助(其它函數式的語言也有),可以讓你的程式碼更簡潔,更易讀。我們再來看一個比較複雜的例子:#計算陣列中正整數的值number =[2, -5, 9, -7, 2, 5, 4, -1, 0, -3, 8 ] count = 0 sum = 0for i in range(len(number)):
if number[i]>0: count += 1 sum += number[i]print sum,countif count>0: average = sum/countprint average#==========輸出==========30 6 5如果用函數式編程,這個範例可以寫成這樣:
number =[2, -5, 9, -7, 2, 5, 4, -1, 0, -3, 8] sum = filter(lambda x: x>0, number) average = reduce(lambda x,y: x+y, sum)/len(sum)print average#========輸出===========5最後我們可以看到,函數式程式設計有以下好處:1)程式碼更簡單了。
2)資料集,操作,回傳值都放到了一起。
3)你在讀程式碼的時候,沒有了循環體,於是就可以少了些臨時變量,以及變數倒來倒去邏輯。
4)你的程式碼變成了在描述你要幹嘛,而不是怎麼去乾。
以上是python-函數式程式設計實例教程的詳細內容。更多資訊請關注PHP中文網其他相關文章!

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,減法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

SublimeText3漢化版
中文版,非常好用

記事本++7.3.1
好用且免費的程式碼編輯器

Dreamweaver Mac版
視覺化網頁開發工具