[英]What is the difference between these two lambda functions in Python?
在以下 python 代碼中,兩個 lambda 函數返回相同的值,即 x:
x = [2 , 3 , 4 , 5 , 6 , 7 , 8]
print(lambda x: x == 2)
print(lambda x: x if x == 2 else None)
據我了解,第一個 lambda function 也是一個 if 語句,但我不太明白它的語法。
第一個將返回 boolean 值( True
或False
),而第二個將返回2
或None
,具體取決於x == 2
與否。
第一個與以下代碼相同:
def f(x):
return (x == 2) # returns either True or False
但第二個與此代碼相同:
def f(x):
if (x == 2):
return (x)
# if the code takes this path, x will always be 2 when it's returned
else:
return (None)
# None is not the same as false
請參閱此帖子了解None
和False
之間的區別
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.