1.not a
是判断a是否为0、false、空字符串、空列表、空字典、空元组以及none,满足任一条件即返回true
2.is和is not
是不是某种对象
3.is not none和is none
none:在python中是一个单例对象,一个特殊的常量:没有值、空值、值不存在
对于在判断条件中的对象值的判断,除了false外,none、0、数据为空[]、""、{}、()都是false,即bool(none)、bool(0)、bool([])、bool("")、bool({})、bool(())的值均为false
可以认为判断一个变量是否为none, none 可以认为是一个特定的变量, 只要没有被设定为 none 的变量都返回 true, 例如pytorch 中, 对于一些 no_grad 的变量, 它们的 a.grad = none
4.实例
a = [] b = none c = [1, 2] print(a is not none) print(b is not none) print(c is not none) print('*' * 10) print(not a) print(not b) print(not c) >>true >>false >>true >>********** >>true >>true >>false
if val: print('if val') if not val: print('if not val') if val is not none: print('if val is not none') if val is none: print('if val is none')
val为none时:
if not val
if val is none
val为false时:
if not val
if val is not none
val为0时:
if not val
if val is not none
val为1时:
if val
if val is not none
val为[]空列表时:
if not val
if val is not none
val为[1,2]非空列表时:
if val
if val is not none
val为某具体对象时:
if val
if val is not none
附:python中 is none与== none的区别
我们知道对象中有__eq__函数,用于判断两个对象的值是否相等;但是__eq__函数是可以被我们自己定义的。比如我们让__eq__函数用于返回ture。
但是is判断的是两个对象的id是否相等,即判断a对象是否是b对象。
python中数值类型(int,float),str字符串,tuple都是不可变类型。
python中none是一个特殊的常量,“不同的”none的id是一样的。
所以当判断数据结构中的某一直是否为none时,is会更好一些。
(is函数比==要快一些,不用运行查找和比较函数)
总结
到此这篇关于python条件判断中not、is、is not、is not none、is none的文章就介绍到这了,更多相关python条件判断实例内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论