gpt4 book ai didi

Python:防止 "if"楼梯?

转载 作者:太空宇宙 更新时间:2023-11-03 12:13:58 26 4
gpt4 key购买 nike

每当我编写需要大量条件的代码时,我都会这样做:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com