修路挖出16.7米蛇精,台服痞子狼,小松原绫音
代码中经常会有变量是否为none的判断,有三种主要的写法:
if x is none
;if not x:
;if not x is none
(这句这样理解更清晰if not (x is none)
) 。如果你觉得这样写没啥区别,那么你可就要小心了,这里面有一个坑。先来看一下代码:
>>> 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, 空列表[], 空字典{}, 空元组()都相当于false ,即:
代码如下:
not none == not false == not '' == not 0 == not [] == not {} == not ()
因此在使用列表的时候,如果你想区分x==[]和x==none两种情况的话, 此时if not x:
将会出现问题:
>>> 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==[]
的情况也判断进来了,此种情况下将无法区分。
对于习惯于使用if not x这种写法的pythoner,必须清楚x等于none, false, 空字符串"", 0, 空列表[], 空字典{}, 空元组()时对你的判断没有影响才行。
而对于if x is not none
和if not x is none
写法,很明显前者更清晰,而后者有可能使读者误解为if (not x) is none
,因此推荐前者,同时这也是谷歌推荐的风格
结论:
if x is not none
是最好的写法,清晰,不会出现错误,以后坚持使用这种写法。
使用if not x这种写法的前提是:必须清楚x等于none, false, 空字符串"", 0, 空列表[], 空字典{}, 空元组()时对你的判断没有影响才行。
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
python求numpy中array按列非零元素的平均值案例
网友评论