1

我严重睡眠不足,我需要帮助来重写这个小的 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()

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

4

3 回答 3

6

else从分支匹配的条件开始。它是a, or b, or之一c and d,因此您需要在此处使用orandnot来表示何时else选择原始代码的分支:

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

然后,您可以通过应用德摩根定律之一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()

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

于 2013-12-10T10:16:30.143 回答
1

continue不能在 if 语句中工作。所以我假设你在一个循环(while 或 for)中运行它。试试这个:

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

没有 not 的第二种方法是:

if a or b or (c and d):
    continue
else:
    e()

正如 M. Martjin Peters 在评论中解释的那样,第二种方法中的 else 块是不必要的。您可以删除 else 并将 e() 移到 if 块之外。但是,在我看来, if 之后的 else 将使代码更具可读性。

第二种方法也可以写成:

if a or b or (c and d):
    continue
e()
于 2013-12-10T10:20:22.813 回答
1
if not any((a, b, (c and d))):
    e()
于 2013-12-10T10:22:32.317 回答