加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python:防止“if”楼梯?

发布时间:2020-12-20 12:42:02 所属栏目:Python 来源:网络整理
导读:每当我编写需要大量条件的东西时,我最终会这样做: if foo: if bar: if foobar: if barfoo: if foobarfoo: if barfoobar: # And forever and ever and ever 我不能写如果foo和bar和foobar和…因为我在一个if的某个地方检查了值列表元素(如果foo [1] ==’bar
每当我编写需要大量条件的东西时,我最终会这样做:

if foo:
  if bar:
    if foobar:
      if barfoo:
        if foobarfoo:
          if barfoobar:
            # And forever and ever and ever

我不能写如果foo和bar和foobar和…因为我在一个if的某个地方检查了值列表元素(如果foo [1] ==’bar’),如果列表索引没有不存在,我得到一个错误.

是否有条件检查这样的事情或替代方法的快捷方式?谢谢.

解决方法

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和短路.如果表达式的左侧为false,则根本不评估右侧.

foo = dict()

if 'bar' in foo and foo['bar']:
    doSomething()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读