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

标签 python logic control-flow equivalence

我严重失眠,我需要帮助重写这个 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 分支在什么条件下匹配开始。它是 abc 和 d 之一,因此您需要使用 not 表示何时选择原始代码的 else 分支:

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

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

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()

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

关于python - 一系列 if else if else 子句的逻辑等价,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20491643/

相关文章:

python - 将特定的输入文件提供给mapper和reducer hadoop

javascript - 循环十六进制值的更合适的方法

java - 交替多次try catch处理异常

python - psycopg2.ProgrammingError : syntax error at end of input

Python:为什么 ("hello"是 "hello")评估为真?

python - 在 Python 中动态评估简单的 boolean 逻辑

Ruby/cup 排序算法不会检查字符串是否为整数

python - threading.Thread 中的流控制

java - 如何在 Java 中管理复杂的流程控制?

Python xlrd - 具有受密码保护的工作表的 open_workbook 方法