每当我编写需要大量条件的代码时,我都会这样做:
if foo:
if bar:
if foobar:
if barfoo:
if foobarfoo:
if barfoobar:
# And forever and ever and ever
我不能写 if foo and bar and foobar and ...
因为我检查值列表元素(if foo[1] == 'bar'
) 在 if
的某处,如果列表索引不存在,我会得到一个错误。
是否有条件检查此类事情的捷径或替代方法?谢谢。
最佳答案
I can't write if foo and bar and foobar and ... because I call list elements inside of an if somewhere down the line, and if the list index don't exist, I get an error.
在python中,和
短路。如果表达式的左侧为假,则根本不对右侧求值。
foo = dict()
if 'bar' in foo and foo['bar']:
doSomething()
关于Python:防止 "if"楼梯?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4975457/