2012-10-04 34 views
13

帶有布爾值的列表索引工作正常。 雖然索引應該是一個整數。Python Bool和int比較和帶有布爾值的列表索引

以下是我的嘗試在控制檯:

>>> l = [1,2,3,4,5,6] 
>>> 
>>> l[False] 
1 
>>> l[True] 
2 
>>> l[False + True] 
2 
>>> l[False + 2*True] 
3 
>>> 
>>> l['0'] 
Traceback (most recent call last): 
File "<stdin>", line 1, in <module> 
TypeError: list indices must be integers, not str 
>>> type(True) 
<type 'bool'> 

當我試圖l['0']它打印出的整型預期指數,這是明顯的錯誤。 然後,即使'True''False'的類型爲Bool,列表上的索引工作正常,並自動將其轉換爲int類型並執行操作。

請解釋一下內部發生了什麼。 我是第一次發佈問題,所以請原諒我的任何錯誤。

回答

20

發生什麼事是布爾人實際上整數。 True是1,False是0. Bool是int的子類型。

>>> isinstance(True, int) 
True 
>>> issubclass(bool, int) 
True 

所以它不會將它們轉換爲整數,它只是將它們用作整數。因爲歷史原因,Bools是整數,在Python中存在一個bool類型之前,人們使用整數0表示false,而1表示true,因此當他們添加一個bool類型時,他們按順序創建了布爾值整數以維持與舊代碼,使用這些整數值的向後兼容性。參見例如http://www.peterbe.com/plog/bool-is-int。)

>>> help(True) 
Help on bool object: 

class bool(int) 
| bool(x) -> bool 
| 
| Returns True when the argument x is true, False otherwise. 
| The builtins True and False are the only two instances of the class bool. 
| The class bool is a subclass of the class int, and cannot be subclassed. 
+2

+1,我學到了一些東西。不知道'bool'是'int'的一個子類。 – nneonneo

+0

我剛剛通過這篇文章[鏈接] http://stackoverflow.com/questions/3174392/is-it-pythonic-to-use-bools-as-ints/3175293#3175293) 非常感謝。 – Somesh

2

...布爾是普通整數的子類型。

Source

正如你所看到的,False0True1

2

Python 使用缺少布爾值,我們只使用整數,0表示False,其他整數表示True。所以當布爾語被添加到語言中時,值False和True可以被解釋器視爲整數值0和1,以幫助向後兼容。在內部,它們是int的子類。

換句話說,下面的公式成立:

>>> False == 0 
True 
>>> True == 1 
True 

,當你發現:

>>> True * 3 
3 

這並不延伸然而字符串。