如何使嵌套的IF语句更整洁 [英] How to make nested IF statements neater
问题描述
这个问题可以用语言独立的方式提出,但我在python的上下文中提问,因为不同的语言会有不同的细微差别。
This question could be asked in a language independent way but I'm asking in the context of python since different languages will have different nuances.
我认识到这一点类似于这个问题,但我认为我的是不同之处在于我在询问将两个条件与&
放在同一if语句中的情况会产生错误。
I recognize that this is similar to this question but I think mine is different in that I'm asking about a case where putting the two conditions in the same if statement with &
will generate an error.
假设我想看看 abc [x]
是否等于'fish'但是我要说我不确定 len(abc)
是> =到x。我不能只有如果abc [x] =='fish'
因为它可能是索引超出范围。因此我需要做
Let's say I want to see if abc[x]
is equal to 'fish' but let's say I don't know for sure that len(abc)
is >= to x. I can't just have if abc[x]=='fish'
because it might be index out of range. As such I need to do
if len(abc)>x:
if abc[x]=='fish':
dostuff
else:
dootherstuff
else:
dootherstuff
有没有更简洁的方法可以做到这一点,我没有两个其他语句最终做同样的 dootherstuff
?如果我想改变什么 dootherstuff
晚于我必须在两个地方改变它,但到那时我可能会忘记。当然我可以尝试评论代码以便稍后提醒自己或者使用 dootherstuff
一个函数,但这仍然是第二好的。很多时候,当我结束这个时, dootherstuff
只是一行代码,因此即使它解决了后续的变化,使它成为一个函数并不会感觉好多少场景。
Is there a cleaner way to do this where I don't have two else statements that end up doing the same dootherstuff
? If I want to change what dootherstuff
is later than I have to change it in both places but by then I might forget. Sure I could try to comment the code to remind myself later or make dootherstuff
a function but that still seems second best. A lot of times when I wind up doing this the dootherstuff
is just a one line of code so making it a function doesn't feel much better even though it addresses the subsequent change scenario.
推荐答案
当然,这是:
if len(abc) > x and abc[x] == 'fish':
dostuff
else:
dootherstuff
和
短路,所以 abc [x] =='fish'
只会如果 len(abc)>则进行评估x
是 True
。大多数语言都有类似的运算符(例如,C中的&&
)。
and
short-circuits, so abc[x] == 'fish'
will only be evaluated if len(abc) > x
is True
. Most languages have a similar operator (e.g. &&
in C).
&
用于按位和,并且不会短路,所以请勿使用那。
&
is for bitwise "and," and doesn't short-circuit, so don't use that.
这篇关于如何使嵌套的IF语句更整洁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!