可能重複:
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