如何在Python中引用空对象?


当前回答

上面的答案只会为None的结果为True,但存在float('nan')这样的东西。你可以使用pandas isnull:

>>> import pandas as pd
>>> pd.isnull(None)
True
>>> pd.isnull(float('nan'))
True
>>> pd.isnull('abc')
False
>>> 

或者没有熊猫:

>>> a = float('nan')
>>> (a != a) or (a == None)
True
>>> a = None
>>> (a != a) or (a == None)
True
>>> 

这样做的原因是float('nan') != float('nan'):

>>> float('nan') == float('nan')
False
>>> float('nan') != float('nan')
True
>>> 

其他回答

上面的答案只会为None的结果为True,但存在float('nan')这样的东西。你可以使用pandas isnull:

>>> import pandas as pd
>>> pd.isnull(None)
True
>>> pd.isnull(float('nan'))
True
>>> pd.isnull('abc')
False
>>> 

或者没有熊猫:

>>> a = float('nan')
>>> (a != a) or (a == None)
True
>>> a = None
>>> (a != a) or (a == None)
True
>>> 

这样做的原因是float('nan') != float('nan'):

>>> float('nan') == float('nan')
False
>>> float('nan') != float('nan')
True
>>> 

在Python中,“null”对象是单例None。

要检查某个值是否为None,使用is标识符:

if foo is None:
    ...

在Python中处理“空”元素的简单函数:

代码:

def is_empty(element) -> bool:
    """
    Function to check if input `element` is empty.

    Other than some special exclusions and inclusions,
    this function returns boolean result of Falsy check.
    """
    if (isinstance(element, int) or isinstance(element, float)) and element == 0:
        # Exclude 0 and 0.0 from the Falsy set.
        return False
    elif isinstance(element, str) and len(element.strip()) == 0:
        # Include string with one or more empty space(s) into Falsy set.
        return True
    elif isinstance(element, bool):
        # Exclude False from the Falsy set.
        return False
    else:
        # Falsy check.
        return False if element else True

测试:

print("Is empty?\n")
print('"" -> ', is_empty(""))
print('"      " -> ', is_empty("      "))
print('"A" -> ', is_empty("A"))
print('"a" -> ', is_empty("a"))
print('"0" -> ', is_empty("0"))
print("0 -> ", is_empty(0))
print("0.0 -> ", is_empty(0.0))
print("[] -> ", is_empty([]))
print("{} -> ", is_empty({}))
print("() -> ", is_empty(()))
print("[1, 2] -> ", is_empty([1, 2]))
print("(3, 5) -> ", is_empty((3, 5)))
print('{"a": 1} -> ', is_empty({"a": 1}))
print("None -> ", is_empty(None))
print("True -> ", is_empty(True))
print("False -> ", is_empty(False))
print("NaN -> ", is_empty(float("nan")))
print("range(0) -> ", is_empty(range(0)))

输出:

Is empty?

"" ->  True
"      " ->  True
"A" ->  False
"a" ->  False
"0" ->  False
0 ->  False
0.0 ->  False
[] ->  True
{} ->  True
() ->  True
[1, 2] ->  False
(3, 5) ->  False
{"a": 1} ->  False
None ->  True
True ->  False
False ->  False
NaN ->  False
range(0) ->  True

Null是一个特殊的对象类型,比如:

>>>type(None)
<class 'NoneType'>

你可以检查一个对象是否在类'NoneType'中:

>>>variable = None
>>>variable is None
True

更多信息可以在Python文档中找到

根据真值测试,'None'直接测试为FALSE,所以最简单的表达式就足够了:

if not foo: