天天看點

Python函數式程式設計(map、reduce、filter、lambda)

map 對清單每個元素進行函數計算、 reduce 對清單中元素之間進行計算、filter挑選符合條件的清單元素、lambda匿名函數 1、對多個數進行函數運算 import math def add(x, y, f):     return f(x) + f(y) print (add(25, 9, math.sqrt)) 傳回:7

2、 map() 是 Python 内置的高階函數,它接收一個 函數 f  和一個  list ,并通過把函數 f 依次作用在 list 的每個元素上,得到一個新的 list 并傳回。

假設使用者輸入的英文名字不規範,沒有按照首字母大寫,後續字母小寫的規則,請利用map()函數,把一個list(包含若幹不規範的英文名字)變成一個包含規範英文名字的list:

輸入:['adam', 'LISA', 'barT'] 輸出:['Adam', 'Lisa', 'Bart'] 方法一: def format_name(s):     t=s.lower()     l=t.title()     return l 方法二: def format_name(s):     return s[0].upper()+s[1:].lower() ### 因為在python3裡面,map(),filter()這些的傳回值已經不再是list,而是iterators, 是以想要使用,隻用将iterator 轉換成list 即可, 比如  list(map())  print (list(map(format_name, ['adam', 'LISA', 'barT'])))

任務: list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])) 輸出:[1, 4, 9, 16, 25, 36, 49, 64, 81] def square ( x ) : # 計算平方數 ...      return x ** 2 map ( square , [ 1 , 2 , 3 , 4 , 5 ] ) # 計算清單和:\ [ 1 , 4 , 9 , 16 , 25 ] map ( lambda x : x ** 2 , [ 1 , 2 , 3 , 4 , 5 ] ) # 使用 lambda 匿名函數 [ 1 , 4 , 9 , 16 , 25 ]

3、 reduce()函數接收的參數和 map()類似, 一個函數 f,一個list ,但行為和 map()不同,reduce()傳入的函數 f 必須接收兩個參數,reduce()對list的每個元素反複調用函數f,并傳回最終結果值。 reduce已經取消了,如想使用,可以用fuctools.reduce來調用。但是要先導入fuctools, 即輸入:import fuctools 

Python内置了求和函數sum(),但沒有求積的函數,請利用recude()來求積:

輸入:[2, 4, 5, 7, 12] 輸出:2*4*5*7*12的結果 import fuctools def prod(x, y):     return x*y print (list(fuctools.reduce(prod, [2, 4, 5, 7, 12])))

4、 filter()函數接收一個 函數 f  和一個 list ,這個函數 f 的作用是對每個元素進行判斷,傳回 True或 False, filter()根據判斷結果自動過濾掉不符合條件的元素,傳回由符合條件元素組成的新list。

請利用filter()過濾出1~100中平方根是整數的數,即結果應該是:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100] import math def is_sqr(x):     return math.sqrt(x)%1==0    ##或return int(math.sqrt(x))==math.sqrt(x)

print (list(filter(is_sqr, range(1, 101))))

5 、sorted()

 sorted()也是一個高階函數,它可以接收一個比較函數來實作自定義排序,比較函數的定義是,傳入兩個待比較的元素 x, y,如果 x 應該排在 y 的前面,傳回 -1,如果 x 應該排在 y 的後面,傳回 1。如果 x 和 y 相等,傳回 0。

是以,如果我們要實作倒序排序,隻需要編寫一個reversed_cmp函數:

def reversed_cmp(x, y):
    if x > y:
        return -1
    if x < y:
        return 1
    return 0
      

這樣,調用 sorted() 并傳入 reversed_cmp 就可以實作倒序排序:

>>> sorted([36, 5, 12, 9, 21], reversed_cmp) [36, 21, 12, 9, 5]

任務:将清單元素大小排序,不考慮大小寫 a = ['bob', 'about', 'Zoo', 'Credit'] print(sorted(a, key=str.lower)) 輸出:['about', 'bob', 'Credit', 'Zoo']

6、python中匿名函數(lambda x://)

在Python中,對匿名函數提供了有限支援。還是以map()函數為例,計算 f(x)=x2 時,除了定義一個f(x)的函數外,還可以直接傳入匿名函數:

>>> list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
[1, 4, 9, 16, 25, 36, 49, 64, 81]
      

通過對比可以看出,匿名函數 lambda x: x * x 實際上就是:

def f(x):
    return x * x
      

關鍵字lambda 表示匿名函數,冒号前面的  x 表示函數參數。 匿i名函數有個限制,就是 隻能有一個表達式, 不寫return,傳回值就是該表達式的結果。 ###定義一個絕對值函數 myabs = lambda x: -x if x < 0 else x myabs(-1) 輸出:1 任務:去掉清單中空的元素 print(list(filter(lambda s: s and len(s.strip()) > 0, ['test', None, '', 'str', '  ', 'END']))) 輸出:['test', 'str', 'END']

或者lst = ['test', None, '', 'str', '  ', 'END'] list(filter((lambda x : x != None and len(x.strip())>0),lst)) 輸出:['test', 'str', 'END']

等價于: def is_not_empty(s):

    return s and len(s.strip()) > 0 list(filter(is_not_empty, ['test', None, '', 'str', '  ', 'END']))

繼續閱讀