What is the difference between “is” and “==” in python?
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
Python ‘==’ vs ‘is’ comparing strings, ‘is’ fails sometimes, why?
是
1 | a == b |
一样
1 | a is b |
?
如果没有,有什么区别?
编辑:为什么
1 2 | a = 1 a is 1 |
返回true,但是
1 2 | a = 100.5 a is 100.5 |
返回错误?
不,这些不一样。
1 2 3 4 5 6 7 8 9 10 11 | a = 100.5 a is 100.5 # => False a == 100.5 # => True a = [1,2,3] b = [1,2,3] a == b # => True a is b # => False a = b a == b # => True a is b # => True, because if we change a, b changes too. |
所以:如果你的意思是对象应该代表相同的东西(最常见的用法),那么使用
另外,您可以通过
正如上面已经很清楚地解释过的。
is : used for identity testing (identical 'objects')
== : used for equality testing (~~ identical value)
还请记住,python使用字符串内接(作为优化),因此您可以得到以下奇怪的副作用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | >>> a ="test" >>> b ="test" >>> a is b True >>>"test_string" is"test" +"_" +"string" True >>> a = 5; b = 6; c = 5; d = a >>> d is a True # --> expected >>> b is a False # --> expected >>> c is a True # --> unexpected |