【问题标题】:Else statement for nested and unnested if嵌套和非嵌套 if 的 else 语句
【发布时间】:2016-01-28 04:54:34
【问题描述】:

我想知道是否有任何方法可以为多个级别的 if 语句设置一个 else 语句。

我会详细说明:

if <condition-1>:
    if <condition-2>:
        do stuff
    elif <condition-3>:
        do other stuff
else: #if either condition-1 or all nested conditions are not met
    do some other thing

我知道这可以通过添加一个带有“做其他事情”的函数并使用嵌套的 else 和顶层 else 调用它来轻松解决,但我想知道是否有某种方法可以做到这一点看起来干净一点。

提前致谢,欢迎提出任何想法。

【问题讨论】:

标签: python if-statement nested nested-if


【解决方案1】:

不,不是真的。这确实是 python 不希望你做的事情。它更喜欢保持可读性和清晰度,而不是“华丽”的技巧。您可以通过组合语句或创建“标志”变量来做到这一点。

例如,你可以这样做

if <condition-1> and <condition-2>:
    # do stuff
elif <condition-1> and <condition-3>:
    # do other stuff
else:
    # do some other thing

或者,如果您出于某种原因不想继续重复条件 1(检查成本很高,不重复它会更清楚,或者您只是不想继续输入它),我们可以做

triggered_condition = False
if <condition-1>:
    if <condition-2>:
        triggered_condition = True
        # do stuff
    elif <condition-3>:
        triggered_condition = True
        # do some other stuff
if not triggered_condition:
    # do some other thing

如果在函数中使用它,我们甚至可以跳过标志

if <condition-1>:
    if <condition-2>:
        # do stuff and return
    elif <condition-3>:
        # do some other stuff and return
# do some other thing
# if we got here, we know no condition evaluated to true, as the return would have stopped execution

【讨论】:

  • 嗯,我就是这么想的,但我想如果你不问你永远不会知道,谢谢你的快速回复!
【解决方案2】:

有几种方法不是特别直观/可读......但工作:

在这个中,我们利用了for ... else ... 语法。任何成功的条件都应该发出中断

for _ in [1]:
    if <condition>:
        if <condition>:
            # where ever we consider ourselves "successful", then break
            <do stuff>
            break
        elif <condition>:
            if <condition>:
                <do stuff>
                break
else:
    # we only get here if nothing considered itself successful

另一种方法是使用try ... else ...,其中“成功”的分支应该引发异常。

这些不是特别好,不推荐!

【讨论】:

  • 我建议不要使用异常捕获方法。这有点滥用其目的,如果嵌套 if 中的任何语句可以正常引发异常,则可能非常不稳定。
  • @Matthew True ...但如果你够讨厌使用异常方法,你就会抛出一个自定义异常。
  • 感谢您的回答,这些方法确实有效,但其想法是提高可读性并删除多余的 else。不过很有创意!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-14
  • 1970-01-01
相关资源
最近更新 更多