Python中a is b和a==b的区别?超详细的介绍来了
陈立鑫
优草派
本篇文章主要给大家详细介绍了在python中a is b和a==b的具体区别,小编讲解得比较详细,大家一定要耐心看完,看完之后一定会有所收获的。那么让我们继续往下看。
a == b ,这是一个比较运算符,它事用于来比较两个对象的value(值)是否相同,相同则返回True 否则返回False
具体事例如下:
# 以下用于示例 a == b 用法 >>> a = 1 # a, b 数值类型 >>> b = 1 >>> a == b True >>> a = 'zhaoxuan'# a,b 字符串类型 >>> b = 'zhaoxuan' >>> a == b True >>> a = [1, 2]# a,b 列表类型 >>> b = [1, 2] >>> a == b True >>> a = 1 # a, b 数值类型 >>> b = 2 >>> a == b False >>> a = 'hello'# a,b 字符串类型 >>> b = 'world' >>> a == b False >>> a = [1, 2]# a,b 列表类型 >>> b = [1, 3] >>> a == b False
2 a is b,用于比较两个对象的物理id。如果相同则返回True,否则返回False
具体事例如下:
# 以下用于示意 a is b 用法: >>> a = -5# a, b 数值类型 >>> b = -5 >>> a is b True >>> a = -6 >>> b = -6 >>> a is b False >>> a = 256 >>> b = 256 >>> a is b True >>> a = 257 >>> b = 257 >>> a is b False >>> b = 'zhaoxuan'# a, b 字符串类型 >>> a = 'zhaoxuan' >>> a is b True# 简单字符串可用 >>> id(a) 42111997 >>> id(b) 42111997 >>> a = 'wo shi zhao xuan' >>> b = 'wo shi zhao xuan' >>> a is b False# 复杂字符串不可用 >>> id(a) 2146074255200 >>> id(b) 2146074255272 >>> a = (1,2,3) # a, b 元组类型 >>> b = (1,2,3) >>> a is b False >>> id(a) 2146074256320 >>> id(b) 2146074256378 >>> a = [1,2,3] #a,b list类型 >>> b = [1,2,3] >>> a is b False >>> a = {'a':1,'b':2} #a,b dict类型 >>> b = {'a':1,'b':2} >>> a is b False >>> a = set([1,2,3])#a,b set类型 >>> b = set([1,2,3]) >>> a is b False >>> id(a) 2146074299258 >>> id(b) 2146074299236
【原创声明】凡注明“来源:优草派”的文章,系本站原创,任何单位或个人未经本站书面授权不得转载、链接、转贴或以其他方式复制发表。否则,本站将依法追究其法律责任。