Skip to main content
 首页 » 编程设计

python之在 python 中编写这个条件是否有更清晰、更短的方法

2025年05月04日2398°冷暖

>>> def accept(d1, d2): 
    if somefunc(d1,d2) > 32: 
        h = 1 
    else: 
        h = 0 
    return h 

Does Python have a ternary conditional operator?没有为想要返回值的情况提供解决方案。基于 lambda 的解决方案是更可取的。

请您参考如下方法:

“返回值场景”与其他场景没有什么不同:

return 1 if somefunc(d1, d2) > 32 else 0 

如果出于某种原因你想要一个 lambda:

lambda d1, d2: 1 if somefunc(d1, d2) > 32 else 0 

请注意,lambda 与使用 def 定义的返回相同内容的函数没有什么不同。 Lambda 只是常规函数。