14

使用布尔值对列表进行索引工作正常。虽然索引应该是一个整数。

以下是我在控制台中尝试过的:

>>> 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']它时,会打印出索引中预期的 int 类型的错误,这很明显。然后,即使是 和 的类型,'True'列表'False'Bool的索引也可以正常工作,并自动将其转换为 int 类型并执行操作。

请解释内部发生的情况。我是第一次发问题,如有错误请见谅。

4

4 回答 4

21

发生的事情是布尔值实际上整数。True 为 1,False 为 0。Bool 是 int 的子类型。

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

所以它没有将它们转换为整数,它只是将它们用作整数。

(由于历史原因,bool 是整数。在 Python 中存在 bool 类型之前,人们使用整数 0 表示假,1 表示真。因此,当他们添加 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.
于 2012-10-04T06:46:27.413 回答
3

Python过去常常缺少布尔值,我们只使用整数,0 表示False,任何其他整数表示True. 因此,当布尔值添加到语言中时,值FalseTrue可以被视为整数值0,并且1仍然由解释器处理,以帮助向后兼容。在内部,bool是 的子类int

换句话说,以下等式为真:

>>> False == 0
True
>>> True == 1
True
>>> isinstance(True, int)
True
>>> issubclass(bool, int)
True

正如你发现的:

>>> True * 3
3

然而,这并没有扩展到字符串。

于 2012-10-04T06:48:35.820 回答
2

...布尔值是普通整数的子类型。

来源

如您所见,Falseis0Trueis 1

于 2012-10-04T06:46:44.913 回答
-1

Python 源文档没有直接提到所有非零整数True在传递给if语句时计算为,而只有零计算为False. 您可以使用以下 Python 代码向自己证明:

for test_integer in range(-2, 3, ):
    if not test_integer:
        print('{} evaluates to False in Python.'.format(test_integer))
    else:
        print('{} evaluates to True in Python.'.format(test_integer))
>>>-2 evaluates to True in Python.
-1 evaluates to True in Python.
0 evaluates to False in Python.
1 evaluates to True in Python.
2 evaluates to True in Python.

尽可能在零的任一侧尝试它;此代码仅显示 -2、-1、0、1 和 2(含)。

于 2020-02-07T22:11:23.443 回答