>>> def accept(d1, d2):
if somefunc(d1,d2) > 32:
h = 1
else:
h = 0
return h
Does Python have a ternary conditional operator?没有为想要返回值的案例提供解决方案。基于λ的溶液是优选的。
答案 0 :(得分:5)
“返回值场景”与其他任何场景都没有区别:
return 1 if somefunc(d1, d2) > 32 else 0
如果由于某种原因你想要一个lambda:
lambda d1, d2: 1 if somefunc(d1, d2) > 32 else 0
请注意,lambda与使用def
定义的函数没有区别,返回相同的内容。 Lambdas只是常规功能。
答案 1 :(得分:3)
或者,也许更棘手,
return int(somefunc(d1, d2) > 32)
请注意int(True) == 1
和int(False) == 0
。
答案 2 :(得分:-1)
变成lambda
(非显式功能):
accept = lambda d1,d2: 1 if somefunc(d1, d2) > 32 else 0