1. 程式人生 > >Python中的lambda的簡單介紹

Python中的lambda的簡單介紹

好的 cto turn 匿名 urn 這樣的 簡單介紹 對象 一個表

在學習python的過程中,lambda的語法經常出現,現在將它整理一下,以備日後查看。   

1、lambda是什麽?

舉個例子如下:

1 func=lambda x:x+1
2 print(func(1))
3 #2
4 print(func(2))
5 #3
6 
7 #以上lambda等同於以下函數
8 def func(x):
9     return(x+1)

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

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

 1 from functools import reduce 
 2 foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]
 3 
 4 print (list(filter(lambda x: x % 3 == 0, foo)))
 5 #[18, 9, 24, 12, 27]
 6 
 7 print (list(map(lambda x: x * 2 + 10, foo)))
 8 #[14, 46, 28, 54, 44, 58, 26, 34, 64]
 9 
10 print (reduce(lambda x, y: x + y, foo))
11 #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的簡單介紹