Skip to main content
 首页 » 编程设计

python之一系列 if else if else 子句的逻辑等价

2025年05月04日18TianFang

我严重失眠,我需要帮助重写这个 Python 小逻辑片段

for _ in range(100): 
    if a: 
        continue 
    elif b: 
        continue 
    elif c and d: 
        continue 
    else: 
        e() 

我想要一个类似的东西

if (some_exprt of a,b,c,d): 
    e() 

我得到的是:

if not a and  not b and (not c or not d): 
   e() 

但我真的不知道这是否正确,对吗?

请您参考如下方法:

从 else 分支在什么条件下不匹配开始。它是 a、b 或 c 和 d 之一,因此您需要使用 或 和 not 表示何时选择原始代码的 else 分支:

if not (a or b or (c and d)): 
    e() 

然后您可以通过应用 one of De Morgan's laws 将 not 放入括号中,将前面的测试更详细地表示为:

if not a and not b and not (c and d): 
    e() 

然后可以进一步扩展为:

if not a and not b and (not c or not d): 
    e() 

这是您自己已经扩展到的。但我会发现第一个版本更具可读性。