Python:防止 "if"楼梯?

标签 python list if-statement

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

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/

相关文章:

python - TensorFlow:恢复多个图

python - 比较Python中的两个未知列表

python - if else 嵌套的更好方法

Mysql if语句选择多行

python - Bash 脚本到 Conda 安装 requirements.txt 与 PIP 跟进

python - 设备代码流 - Microsoft Azure 身份验证

python - 有没有办法将字典解压到 f 字符串 **模板** 中?

python - 如何删除列表列表中的重复值?

python - 列表理解和交集问题

python 根据条件/if else 语句拆分列表