Som*_*esh 14 python indexing boolean list
使用布尔值对列表进行索引工作正常.虽然索引应该是整数.
以下是我在控制台中尝试的内容:
>>> 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'>
Run Code Online (Sandbox Code Playgroud)
当我尝试l['0']打印错误时,指数中预期的int类型,这是显而易见的.然后,即使是类型'True'和'False'存在Bool,名单上的索引工作正常,并自动将其转换成int类型和执行操作.
请解释内部发生的事情.我是第一次发帖,所以请原谅我有任何错误.
Bre*_*arn 21
结果是布尔实际上是整数.True为1,False为0. Bool是int的子类型.
>>> isinstance(True, int)
True
>>> issubclass(bool, int)
True
Run Code Online (Sandbox Code Playgroud)
所以它不是将它们转换为整数,而是将它们用作整数.
(由于历史原因,Bool是整数.在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.
Run Code Online (Sandbox Code Playgroud)