【问题标题】:If statement ordering and key error pythonif语句排序和关键错误python
【发布时间】:2016-06-20 14:49:51
【问题描述】:

即使我检查字典中是否存在密钥,我也会收到一个密钥错误:

def foo(d):
    if (('element' in d.keys()) & (d['element'] == 1)):
        print "OK"

foo({})

documentation我们可以阅读:

表达式 x 和 y 首先计算 x;如果 x 为假,则其值为 回来;否则,对 y 求值,结果值为 返回。

谁能解释一下这种行为?

【问题讨论】:

  • 尝试将 '&' 替换为 'and'
  • 您正在查看and 的文档并执行&,其文档为here(在同一页面上)。
  • 你为什么用空字典调用 foo()?
  • 其实我已经投过简历了,但这可能是重复的:stackoverflow.com/questions/22646463/…

标签: python if-statement dictionary keyerror


【解决方案1】:

& 是“位与”,and 是逻辑“与”运算符,它们不是一回事。

您应该使用and,您还可以删除不需要的括号以提高可读性。

您甚至不必调用keys 方法:

if 'element' in d and d['element'] == 1:

【讨论】:

  • 或者压缩成if d.get('element'):,因为get会自动返回None(这是假的)。
  • 也许if d.get('element') == 1: 保留if 语句的另一部分
猜你喜欢
  • 2018-08-25
  • 1970-01-01
  • 2012-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-21
  • 1970-01-01
  • 2012-08-06
相关资源
最近更新 更多