1. 程式人生 > >python學習手冊(第4版) 第十九章 函式的高階話題

python學習手冊(第4版) 第十九章 函式的高階話題

本章主要涉及遞迴函式、lambda表示式、函式屬性和註解、函數語言程式設計工具(map/filter)

1.遞迴函式:簡單迴圈和迭代

>>> def mysum(L): ...     if not L: ...         return 0 ...     else: ...         return L[0] + mysum(L[1:]) ... >>> mysum([2,1,2,132,1]) 138 >>>

>>> def mysum2(L): ...     first,*rest = L ...     return first if not rest else first + mysum2(rest) ... >>> mysum2([1,2,3,4,5]) 15 >>>

注:遞迴在記憶體空間和執行時間上效率較低

面對多層巢狀,遞迴邏輯更清晰

>>> def sumtree(L): ...     tot = 0 ...     for x in L: ...         if not isinstance(x,list): ...             tot += x ...         else: ...             tot += sumtree(x) ...     return tot ... >>> L = [1,[2,3,4],2,[3,[4,5]]] >>> sumtree(L) 24 >>>

lambda表示式

>>> def func(x,y,z):return x+y+z ... >>> func(1,3,5) 9 >>> f = lambda x,y,z:x+y+z                    # 與上一句的函式等效 >>> f(1,2,3) 6 >>> d = f(1,2,3) >>> d 6 >>> e = func(1,3,5) >>> e 9 >>>

對映函式map

>>> li = [1,3,4] >>> def func(x):return x**2                          # 常規函式 ... >>> list(map(func,li))                 [1, 9, 16] >>> f = lambda x:x**3                                  # lambda表示式的函式也可以配合使用 >>> list(map(f,li)) [1, 27, 64] >>>

>>> def myfunc(f,li):                                # 此函式模擬map實現過程,但map是內建函式,執行效率更高 ...     res = [] ...     for i in li: ...         res.append(f(i)) ...     return res ... >>> myfunc(func,li) [1, 9, 16] >>> myfunc(f,li) [1, 27, 64] >>>

>>> pow(3,3)                                               # pow為內建函式 27 >>> list(map(pow,[1,2,3],[3,4,5]))                 # map搭配內建函式使用    [1, 16, 243] >>>

>>> help(map) Help on class map in module builtins:

class map(object)  |  map(func, *iterables) --> map object                        # 詳細瞭解map,此處可以看出,函式func需要傳入幾個引數,  |                                                                                   # 這裡的 *iteralbes就傳入幾個  |  Make an iterator that computes the function using arguments from  |  each of the iterables.  Stops when the shortest iterable is exhausted.  |  |  Methods defined here:  |  |  __getattribute__(self, name, /)  |      Return getattr(self, name).  |  |  __iter__(self, /)  |      Implement iter(self).  |  |  __new__(*args, **kwargs) from builtins.type  |      Create and return a new object.  See help(type) for accurate signature.  |  |  __next__(self, /)  |      Implement next(self).  |  |  __reduce__(...)  |      Return state information for pickling.

函數語言程式設計工具filter

>>> range(-5,5) range(-5, 5) >>> list(range(-5,5)) [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4] >>> list(filter((lambda x:x>0),range(-5,5)))             # 過濾掉不大於零的數,類似map,filter也是內建函式,執行效率很高 [1, 2, 3, 4] >>>

>>> res = []                                                            >>> for i in range(-5,5):                                       # 使用for迴圈,實現filter同等的效果 ...     if i>0: ...         res.append(i) ... >>> res [1, 2, 3, 4] >>>

函數語言程式設計工具reduce >>> from functools import reduce                    # reduce不是內建函式 >>> reduce((lambda x,y:x+y),[1,2,3,4]) 10 >>> num = 0 >>> for i in [1,2,3,4]:                                          # 使用for迴圈,實現reduce同等的效果 ...     num += i ... >>> num 10 >>>

>>> reduce((lambda x,y:x+y),[],10)                    # reduce可傳入第三個引數,當序列為空時,作為預設值輸出 10 >>>

總結map/filter/reduce

map: 對映函式,根據對映規則(即函式),輸出序列的對映結果,序列長度與對映長度一致

filter: 過濾器,根據過濾規則(即函式),過濾序列的部分,輸出滿足過濾條件的值組成的序列,返回的序列小於等於傳入的序列長度

reduce: 迭代運算,根據運算規則(即函式),對序列逐一進行操作,最後返回一個值,可以傳入第三個引數(如果傳入的序列為空,作為預設值輸出)