Skip to main content
 首页 » 编程设计

python之简化if语句python

2025年05月04日15think

是否有任何 Pythonic 或紧凑的方法来编写以下 if 语句:

if head is None and tail is None: 
    print("Test") 

类似于:

if (head and tail) is None:  

请您参考如下方法:

如果 head 和 tail 都是没有长度或 bool 值的自定义类实例(如 Node() 或类似的),那么只需使用:

if not (head or tail): 

如果以太 head 或 tail 可能是除 None 之外的对象且具有 false-y 值( False、数字 0、空容器等)。

否则,您将陷入显式测试。 bool 逻辑没有“英语语法”捷径。