今天在編程的時候,判斷List是否爲空,我用了一個if list is None:
來判斷,發現List爲空的時候,依然執行不了:
後面的語句。然後修改爲if not x:
就可以了,我們來探究一下,這兩者的區別。
先看一段例子:
>>> x = []
>>> y = None
>>> x is None
False
>>> y is None
True
>>> not x
True
>>> not y
True
>>>
我想判斷x是否爲None,但是卻把x==[]
的情況也判斷進來了,因此if x is None:
無法區分兩種情況。
在Python中 None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元組()都相當於False,因此if not x:
可以適用。
python中的not具體表示是什麼,舉個例子說一下:
在python中not是邏輯判斷詞,用於布爾型True和False,not True爲False,not False爲True,以下是幾個常用的not的用法:
(1) not與邏輯判斷句if連用,代表not後面的表達式爲False的時候,執行冒號後面的語句。比如:
a = False
if not a: # (這裏因爲a是False,所以not a就是True)
print "hello"
這裏就能夠輸出結果hello
(2) 判斷元素是否在列表或者字典中,if a not in b,a是元素,b是列表或字典,這句話的意思是如果a不在列表b中,那麼就執行冒號後面的語句,比如:
a = 5
b = [1, 2, 3]
if a not in b:
print "hello"
這裏也能夠輸出結果hello
總結:
not x
意思相當於:
if x is false:
then True
else:
False