lambda在python中的意思_Python中的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
可以直接做一個迭代用
print(list(map(lambda x: 3, range(0,4))))
# [3, 3, 3, 3]
# x不做任何變量,3可以是函數不需要x一定是函數變量
上面例子中的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的方式更容易理解。
總結
以上是生活随笔為你收集整理的lambda在python中的意思_Python中的lambda的简单介绍的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 参数_Python函数-参
- 下一篇: python等差数列末项计算_Pytho