为什么即使类型匹配,这个 lambda 函数总是 return False?
Why does this lambda function always return False even when the type matches?
鉴于:
type(m[11].value)
<class 'NoneType'>
type(m[12].value)
<class 'str'>
为什么当我将上面的两个变量传递给下面的 lambda 函数时,它总是 return false?
g = lambda x: type(x) is None
您正在检查对象的 类型 是否为 None
,而不是实际对象本身。 type
returns 一个 type
对象,该对象的实际 type/class。在 None
的特殊情况下,它 returns 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
函数直接提供了此功能。
鉴于:
type(m[11].value)
<class 'NoneType'>
type(m[12].value)
<class 'str'>
为什么当我将上面的两个变量传递给下面的 lambda 函数时,它总是 return false?
g = lambda x: type(x) is None
您正在检查对象的 类型 是否为 None
,而不是实际对象本身。 type
returns 一个 type
对象,该对象的实际 type/class。在 None
的特殊情况下,它 returns 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
函数直接提供了此功能。