from:https://www.cnblogs.com/AlwaysWIN/p/6202320.html
在學習python的過程中,lambda的語法時常會使人感到困惑,lambda是什么,為什么要使用lambda,是不是必須使用lambda?
下面就上面的問題進行一下解答。
1、lambda是什么?
看個例子:
func=lambda x:x+1
print(func(1))
#2
print(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的方式更容易理解。