我想知道是否有任何方法为多个级别的if语句提供一条其他语句。
我将详细说明:
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和toplevel调用它,但是我想知道是否有什么方法可以让这个看起来更干净一些。
预先谢谢,欢迎有任何想法。
发布于 2016-01-28 04:56:57
不,不是真的。这正是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发布于 2016-01-28 05:06:17
有几种方法不是特别直观/可读的.但工作:
在这个例子中,我们利用了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 ...,其中“成功”的分支应该会引发异常。
这些不是特别好,是不推荐的!
https://stackoverflow.com/questions/35053136
复制相似问题