Loading... `None`的本质表示的一个**空对象** ```python >> [] == None >> False >> {} == None >> False >> [] is None >> False >> {} is None >> False ``` 在前面回忆到,`is`是身份运算符,`==`是赋值运算符 它们分别表示 **内存地址是否一致**, **值是否相等** 所以,一个列表对象会与一个None对象相等吗? 内存地址会一致吗?显然是不可能的,所以都为`False` 在实际开发中,可能会有这些的写法 ``` def func(): # ... return ``` 一个函数的返回值可能是None,也可能是其他的对象(比如列表) 然后以下面这种方式来判空 ``` f = func() if f is None: pass ``` 显然这是成立的。 --- 但是更加推荐使用`not`关键字 ``` f = func() if not f: pass ``` 如果`f`的值是列表为空,或者是None,都将满足`not f` ``` In [27]: not [] Out[27]: True In [28]: not None Out[28]: True ``` **面试题:用函数的方式过滤空对象** ``` In [31]: l = ['python', '', [], set(), {}, (), 'hello'] ...: list(filter(lambda x:x, l)) Out[31]: ['python', 'hello'] ``` 稍微改改,过滤掉非空对象,很简单啦,使用`not`关键字即可 ``` In [30]: list(filter(lambda x:not x, l)) Out[30]: ['', [], set(), {}, ()] ``` Last modification:August 25th, 2020 at 03:26 pm © 允许规范转载