【问题标题】:Dictionary Truth Value Testing [duplicate]字典真值测试[重复]
【发布时间】:2018-12-31 12:17:50
【问题描述】:
>>> dict = {}
>>> a=2
>>> if a is not None and dict is None:
...     print("lol")
... else:
...     print(" Print result is a")
... 
   result is a

为什么第一个if statement does not run? I am specifying that thedictis empty and that"a"`存在。

参考:https://docs.python.org/2/library/stdtypes.html#truth-value-testing

【问题讨论】:

  • {} 不是NoneNoneNone

标签: python python-3.x dictionary false-positive truthiness


【解决方案1】:

我指定 dict 为空且存在“a”。

不,你不是。您正在测试a 是否与None 不同(真)以及{} 是否与None 相同(假)。

你想要的是a and not d。您几乎不想与布尔值进行比较,当然也不想与 is 进行比较。

【讨论】:

  • 谢谢,这解决了很多困惑! :)
【解决方案2】:

因为字典不是None

假值与满足is None 之间存在差异。

直接测试真实性:

if a is not None and not dict:

正如 cmets 中所述,不要将变量命名为与现有函数名称相同的名称。那只是要求将来出现'dict' object is not callable 错误。

【讨论】:

  • 不会使用dict 作为变量名
  • @RafaelC 为了清楚起见,我使用与 OP 相同的名称。我会添加注释。
猜你喜欢
  • 1970-01-01
  • 2020-07-03
  • 1970-01-01
  • 1970-01-01
  • 2019-07-18
  • 2022-11-15
  • 2018-01-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多