可能重复:
Python “is” operator behaves unexpectedly with integers为什么不能用“is”来比较数字?
我通常使用type(x) == type(y)
进行比较,如果类型相同。然后使用x==y
来比较数值是否相等。
但是,有人提议可以只使用z1 is z2
来比较z1
和z2
是否包含具有完全相同值的相同类型的数字。在很多情况下,它会成功(特别是对于正面整数)。
但是,有时相同的数字(主要是负整数)可能有几个不同的实例。这是python的预期行为吗?
例如:
>>> for x in range(-20,125):
z1=x
z2=int(float(x))
if z1 is not z2:
print "z1({z1}; type = {typez1}; id={idz1}) is not z2({z2}; type = {typez2}; id={idz2})".format(z1=z1,typez1=type(z1),idz1=id(z1),z2=z2,typez2=type(z2),idz2=id(z2))
z1(-20; type = <type 'int'>; id=33869592) is not z2(-20; type = <type 'int'>; id=33870384)
z1(-19; type = <type 'int'>; id=33870480) is not z2(-19; type = <type 'int'>; id=33870408)
z1(-18; type = <type 'int'>; id=32981032) is not z2(-18; type = <type 'int'>; id=33870384)
z1(-17; type = <type 'int'>; id=33871368) is not z2(-17; type = <type 'int'>; id=33870408)
z1(-16; type = <type 'int'>; id=33869712) is not z2(-16; type = <type 'int'>; id=33870384)
z1(-15; type = <type 'int'>; id=33869736) is not z2(-15; type = <type 'int'>; id=33870408)
z1(-14; type = <type 'int'>; id=33869856) is not z2(-14; type = <type 'int'>; id=33870384)
z1(-13; type = <type 'int'>; id=33869280) is not z2(-13; type = <type 'int'>; id=33870408)
z1(-12; type = <type 'int'>; id=33868464) is not z2(-12; type = <type 'int'>; id=33870384)
z1(-11; type = <type 'int'>; id=33868488) is not z2(-11; type = <type 'int'>; id=33870408)
z1(-10; type = <type 'int'>; id=33869616) is not z2(-10; type = <type 'int'>; id=33870384)
z1(-9; type = <type 'int'>; id=33871344) is not z2(-9; type = <type 'int'>; id=33870408)
z1(-8; type = <type 'int'>; id=33869064) is not z2(-8; type = <type 'int'>; id=33870384)
z1(-7; type = <type 'int'>; id=33870336) is not z2(-7; type = <type 'int'>; id=33870408)
z1(-6; type = <type 'int'>; id=33870360) is not z2(-6; type = <type 'int'>; id=33870384)
>>> x
124
>>> print x
124
>>> import sys
>>> print sys.version
2.7.2+ (default, Oct 4 2011, 20:06:09)
[GCC 4.6.1]
http://stackoverflow.com/questions/306313/python-is-operator-behaves-unexpectedly-with-integers也有你的答案 – 2012-07-23 18:43:00
谁提出的?他们应该被打了。 – delnan 2012-07-23 18:43:04
对于一小部分整数,这是真实的(在CPython中)。不应该依赖这种行为,因为它不能保证在python实现中是相同的。 – 2012-07-23 18:56:16