2012-07-23 84 views
4

可能重複:
Python 「is」 operator behaves unexpectedly with integers爲什麼不能用「is」來比較數字?

我通常使用type(x) == type(y)進行比較,如果類型相同。然後使用x==y來比較數值是否相等。

但是,有人提議可以只使用z1 is z2來比較z1z2是否包含具有完全相同值的相同類型的數字。在很多情況下,它會成功(特別是對於正面整數)。

但是,有時相同的數字(主要是負整數)可能有幾個不同的實例。這是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] 
+3

http://stackoverflow.com/questions/306313/python-is-operator-behaves-unexpectedly-with-integers也有你的答案 – 2012-07-23 18:43:00

+6

誰提出的?他們應該被打了。 – delnan 2012-07-23 18:43:04

+1

對於一小部分整數,這是真實的(在CPython中)。不應該依賴這種行爲,因爲它不能保證在python實現中是相同的。 – 2012-07-23 18:56:16

回答

6

是。只有幾個接近於0的數字(正如你發現的那樣比正數多,否則是被編譯器實現爲)。由於表達式可能會導致此範圍之外的數字,因此應使用is從不使用來檢查相等性。

+0

你知道這些數字的範圍嗎? (我相信它是-5到256)。注意到interning行爲不能保證,並且在所有的python實現中可能都不一樣,這也很重要。 – 2012-07-23 18:53:44

+1

@JoelCornett它們真的沒關係,因爲正如你所提到的那樣,它依賴於實現。 – 2012-07-23 18:54:33

+0

表達式的結果是無關緊要的。因爲ints的實現依賴於實現,所以'should'應該用於檢查是否相等(EVER)。 – 2012-07-23 18:55:46

0

is唯一正確的用法是比較對象的身份相同性。要比較價值等同性,請使用==

0

'is'關鍵字比較兩個對象(基本上是存儲它們的內存位置)的標識,而不是值。它不應該用來檢查是否相等。

由於解釋器的具體實現,'is'關鍵字在您的案例中成功了幾次 - 編譯器存儲了一些數字以便於訪問。你不應該期望或依賴這種行爲。

1

按照Python documentation

運營商is和對象標識is not試驗:x is y當且僅當xy是同一對象是真實的。 x is not y產生逆真值。

所以,即使x和y是相同類型並且相等,它們可能不會滿足is關係。

相關問題