gpt4 book ai didi

Python Bool 和 int 比较和索引列表上的 boolean 值

转载 作者:太空狗 更新时间:2023-10-29 17:13:47 31 4
gpt4 key购买 nike

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

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

>>> 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 类型并执行操作。

请解释内部发生的事情。第一次发帖,如有错误请多多包涵。

最佳答案

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

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

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

(由于历史原因, boolean 是整数。在 Python 中存在 bool 类型之前,人们使用整数 0 表示假,1 表示真。因此,当他们添加 bool 类型时,他们将 boolean 值设为整数,以便保持与使用这些整数值的旧代码的向后兼容性。参见例如 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.

关于Python Bool 和 int 比较和索引列表上的 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12721676/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com