python 中 not x 和 x is None 的区别
之前在做LeetCode上的一道题时,用 x is None 时是错的,改成 not x 后,运行通过了,记录下原因
在 python 中,None、False、" "(空字符串)、[] (空列表)、{}(空字典)、( ) (空元组) 都相当于 False
a = []
b = [1]
print(not a, not b) # True False
c = []
d = None
print(c is None, d is None) # False True (可以看到在判空列表时这样写是容易出错的)
print(not c, not d) # True True
e = True
f = False
print(e is None, f is None) # False False
print(not e, not f) # False True
h = ()
print(h is None, not h) # False True
Now is better than never