2024-04-25 00:59:52 发布
网友
下面使用if ... and ...:的代码是否安全,即我们是否确定先测试第一个条件,并且如果键不存在,则忽略第二个条件?在
if ... and ...:
d = {'a': 1} if 'b' in d and d['b'] == 2: print 'hello'
看来是的,因为这不会产生错误。但是所有Python版本都是这样吗?在
它永远不会生成KeyError: 'b'?在
KeyError: 'b'
注:这可能更像Python,没有歧义:
是的,它被称为短路和。在
python2(Link to the doc)和python3.x(Link to the doc)都支持短路and和{}
and
是的,它被称为短路和。在
python2(Link to the doc)和python3.x(Link to the doc)都支持短路}
and
和{相关问题 更多 >
编程相关推荐