这不起作用:
print((lambda : return None)())
Run Code Online (Sandbox Code Playgroud)
但这样做:
print((lambda : None)())
Run Code Online (Sandbox Code Playgroud)
为什么?
Lambda 只能执行表达式并返回执行语句的结果,返回的是语句。
考虑使用or和and运算符来短路结果,以获得将由 lambda 返回的值的更大灵活性。请参阅下面的一些示例:
# return result of function f if bool(f(x)) == True otherwise return g(x)
lambda x: f(x) or g(x)
# return result of function g if bool(f(x)) == True otherwise return f(x).
lambda x: f(x) and g(x)
Run Code Online (Sandbox Code Playgroud)