Python中的lambda的簡單介紹

來源:互聯網
上載者:User

標籤:pytho   too   理解   cto   遍曆   好的   lambda   作用   使用   

1、lambda是什嗎?
func=lambda x:x+1print(func(1))#2print(func(2))#3#以上lambda等同於以下函數def func(x):    return(x+1)

可以這樣認為,lambda作為一個運算式,定義了一個匿名函數,上例的代碼x為入口參數,x+1為函數體。在這裡lambda簡化了函數定義的書寫形式。是代碼更為簡潔,但是使用函數的定義方式更為直觀,易理解。

  Python中,也有幾個定義好的全域函數方便使用的,filter, map, reduce。

from functools import reduce foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]print (list(filter(lambda x: x % 3 == 0, foo)))#[18, 9, 24, 12, 27]print (list(map(lambda x: x * 2 + 10, foo)))#[14, 46, 28, 54, 44, 58, 26, 34, 64]print (reduce(lambda x, y: x + y, foo))#139

  

上面例子中的map的作用,非常簡單清晰。但是,Python是否非要使用lambda才能做到這樣的簡潔程度呢?在對象遍曆處理方面,其實Python的for..in..if文法已經很強大,並且在易讀上勝過了lambda。   

  比如上面map的例子,可以寫成:print ([x * 2 + 10 for x in foo]) 非常的簡潔,易懂。   

      filter的例子可以寫成:print ([x for x in foo if x % 3 == 0]) 同樣也是比lambda的方式更容易理解。

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.