【问题标题】:Why does this lambda function always return False even when the type matches?为什么即使类型匹配,这个 lambda 函数也总是返回 False?
【发布时间】:2018-03-26 07:14:39
【问题描述】:

给定:

type(m[11].value)
<class 'NoneType'>

type(m[12].value)
<class 'str'>

为什么当我将上面的两个变量传递给它时,下面的 lambda 函数总是返回 false?

g = lambda x: type(x) is None

【问题讨论】:

  • &gt;&gt;&gt; type(None) is None 计算结果为 False
  • 因为&lt;class 'NoneType'&gt;None 不是同一个对象。 type(None)&lt;class 'NoneType'&gt;。但是你也可以使用x is None
  • 我受到这篇文章的影响:stackoverflow.com/questions/23086383/…

标签: python python-3.x nonetype


【解决方案1】:

您正在检查对象的 type 是否为None,而不是实际对象本身。 type 返回一个 type 对象,该对象的实际类型/类。在None 的特殊情况下,它返回NoneType

>>> type(None)
NoneType

由于对象有类型,type(x) is None 永远不会计算为True

为什么不直接测试对象?另外,如果你要命名一个lambda,你也可以定义你自己的函数。

>>> def check(x):
...     return x is None
... 
>>> check(None)
True  

或者,您可以使用isinstance 检查 -

>>> isinstance(None, type(None))
True

附带说明一下,pandas 库中的 pd.isnull 函数直接提供此功能。

【讨论】:

    猜你喜欢
    • 2019-05-20
    • 2022-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-30
    相关资源
    最近更新 更多