【发布时间】:2016-07-17 17:41:07
【问题描述】:
为什么可以在 python 中使用布尔值作为索引?例如
>>> a = [1, 2, 3, 4, 5]
>>> a[True]
2
>>> a[False]
1
既然python是一种强类型语言,编译器不应该像将字符串和整数相加一样抛出TypeError吗?例如
>>> "1" + 1
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: cant convert 'int' object to 'str' implicitly
>>> 1 + "1"
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
【问题讨论】:
-
布尔子类整数,正如您在
isinstance(True, int)中看到的那样。