Python中的Lambda運算式小析

來源:互聯網
上載者:User

標籤:python   function   lambda   sorted   匿名函數   

Lambda運算式在Python中經常使用到,在此總結下Lambda運算式的常用方法。


首先,要明白Lambda表達在Python中是作為一個匿名函數的構造器而存在。其次,要明白Lambda運算式的常用情境是Lambda運算式對應函數的使用次數非常有限(因此,沒有必要專門定義一個非匿名函數),同時保證了代碼的簡潔性。


最簡單的一個Lambda運算式例子和對應的非匿名函數:

f = lambda x: x + 1print ( f(1) )
def h (x):return x + 1print ( h(1) )


帶有一個參數的Lambda運算式和對應的非匿名函數:

def f(n):return lambda x: x / nprint ( f(1)(2) ) # n=1; x=2
def g(n):return lambda x: x / nk = g(1)# n=1print ( (k(2)) )# x=2
def h(x,n):return x / nprint ( h(2,1) )#x=2; n=1


Lambda匿名函數經常被用到filter(), map(), reduce(), sorted()函數中,這些函數的共同點是均需要函數型的參數,Lambda運算式正好適用。以sorted函數為例,其key參數指定了一個負責從帶排序的list中抽取comparison key的函數。

club_ranking = [    ('Arsenal', 3),    ('Chelsea', 1),('Manchester City', 2),    ('Manchester United', 4),]club_sorted = sorted(club_ranking, key = lambda x: x[1])   # sort by rankingprint (club_sorted)
'''在Python3.4中需要使用functools將cmp函數轉化為key函數'''import functoolsclub_ranking = [    ('Arsenal', 3),    ('Chelsea', 1),('Manchester City', 2),    ('Manchester United', 4),]def get_ranking( x, y ): #define cmp functionreturn x[1] - y[1]club_sorted = sorted(club_ranking, key = functools.cmp_to_key(get_ranking))   # sort by rankingprint (club_sorted)







Python中的Lambda運算式小析

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.