代碼中經(jīng)常會(huì)有變量是否為None的判斷,有三種主要的寫法:
第一種是`if x is None`;
第二種是 `if not x:`;
第三種是`if not x is None`(這句這樣理解更清晰`if not (x is None)`) 。
如果你覺得這樣寫沒啥區(qū)別,那么你可就要小心了,這里面有一個(gè)坑。先來看一下代碼:
>>> x = 1 >>> not x False >>> x = [1] >>> not x False >>> x = 0 >>> not x True >>> x = [0] # You don't want to fall in this one. >>> not x False
在python中 None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元組()都相當(dāng)于False ,即:
not None == not False == not '' == not 0 == not [] == not {} == not ()
因此在使用列表的時(shí)候,如果你想?yún)^(qū)分x==[]和x==None兩種情況的話, 此時(shí)`if not x:`將會(huì)出現(xiàn)問題:
>>> x = [] >>> y = None >>> >>> x is None False >>> y is None True >>> >>> >>> not x True >>> not y True >>> >>> >>> not x is None >>> True >>> not y is None False >>>
也許你是想判斷x是否為None,但是卻把`x==[]`的情況也判斷進(jìn)來了,此種情況下將無法區(qū)分。
對(duì)于習(xí)慣于使用if not x這種寫法的pythoner,必須清楚x等于None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元組()時(shí)對(duì)你的判斷沒有影響才行。
而對(duì)于`if x is not None`和`if not x is None`寫法,很明顯前者更清晰,而后者有可能使讀者誤解為`if (not x) is None`,因此推薦前者,同時(shí)這也是谷歌推薦的風(fēng)格
結(jié)論:
`if x is not None`是最好的寫法,清晰,不會(huì)出現(xiàn)錯(cuò)誤,以后堅(jiān)持使用這種寫法。
使用if not x這種寫法的前提是:必須清楚x等于None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元組()時(shí)對(duì)你的判斷沒有影響才行。
================================================================
不過這并不適用于變量是函數(shù)的情況,以下轉(zhuǎn)載自:https://github.com/wklken/stackoverflow-py-top-qa/blob/master/contents/qa-control-flow.md
foo is None 和 foo == None的區(qū)別
問題 鏈接
if foo is None: pass
if foo == None: pass
如果比較相同的對(duì)象實(shí)例,is總是返回True 而 == 最終取決于 "eq()"
>>> class foo(object): def __eq__(self, other): return True >>> f = foo() >>> f == None True >>> f is None False >>> list1 = [1, 2, 3] >>> list2 = [1, 2, 3] >>> list1==list2 True >>> list1 is list2 False
另外
(ob1 is ob2) 等價(jià)于 (id(ob1) == id(ob2))
################################################################################
補(bǔ)充,2013.10.09
轉(zhuǎn)自http://zhidao.baidu.com/question/514056244.html
python中的not具體表示是什么,舉個(gè)例子說一下,衷心的感謝
在python中not是邏輯判斷詞,用于布爾型True和False,not True為False,not False為True,以下是幾個(gè)常用的not的用法:
(1) not與邏輯判斷句if連用,代表not后面的表達(dá)式為False的時(shí)候,執(zhí)行冒號(hào)后面的語(yǔ)句。比如:
a = False
if not a: (這里因?yàn)閍是False,所以not a就是True)
print "hello"
這里就能夠輸出結(jié)果hello
(2) 判斷元素是否在列表或者字典中,if a not in b,a是元素,b是列表或字典,這句話的意思是如果a不在列表b中,那么就執(zhí)行冒號(hào)后面的語(yǔ)句,比如:
a = 5
b = [1, 2, 3]
if a not in b:
print "hello"
這里也能夠輸出結(jié)果hello
not x 意思相當(dāng)于 if x is false, then True, else False
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
