2017-04-18 58 views
3

有人可以向我解釋這種語法嗎?我已經通過文檔/博客進行了搜索,但找不到任何使用布爾值作爲陣列切片索引的提及。我發現這句法在這個腳本convert_base.py以布爾值爲索引的數組切片

is_negative = num_as_string[0] == '-' 
num_as_string[is_negative:] 

我的猜測是假被強制轉換爲0,真正被強制轉換爲1。是否有人知道肯定或可能指向我的任何文件?

>>> a = [1,2,3] 
>>> a[True:] 
[2,3] 
>>> a[False:] 
[1,2,3] 
>>> a[:False] 
[] 
>>> a[:True] 
[1] 
>>> a[False:True] 
[1] 
>>> a[True:True] 
[] 
>>> a[False:False] 
[] 
>>> a[True:False] 
[] 
>>> a[False::True+1] 
[1,3] 
+0

最好不要用Python中的「cast」來思考。雖然這個術語通常是鬆散的,但在像Python這樣一個非常動態的語言中,一切都是對象,這是毫無意義的。 –

回答

3

除了事實TrueFalse是由Python切片機構返回用於INT的子類,其很容易分別強制爲1和0,它們的__index__方法10

>>> class Decade(object): 
... def __index__(self): 
...  return 10 
... 
>>> range(20)[Decade():] # list(range(...))[Decade():] for Python 3 
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19] 

>>> True.__index__() 
1 
>>> False.__index__() 
0 

可以與任意對象通過定義__index__方法一般切片

+0

你每天都會學到新的東西。 True + True = 2 – Tristen

+0

謝謝!這個解釋很有幫助。 –

2

TrueFalsebool,的int一個子類的實例。 True具有整數值1,False具有爲整數值0

相關問題