【问题标题】:Using boolean values as array index in python [duplicate]在python中使用布尔值作为数组索引[重复]
【发布时间】: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'

【问题讨论】:

标签: python arrays types


【解决方案1】:

bool 实际上是int 的子类。正如每个数字都是布尔值一样,每个布尔值都是整数。如果你使用int(True),你会得到1,如果你使用int(False),你会得到0。当您使用a[True] 时,它与a[1] 相同。你知道 bool 从这个测试中继承了 int

>>> issubclass(bool, int)
True

【讨论】:

    猜你喜欢
    • 2017-09-14
    • 2016-07-20
    • 2014-06-16
    • 1970-01-01
    • 1970-01-01
    • 2018-05-20
    • 2016-11-21
    • 2013-06-17
    • 1970-01-01
    相关资源
    最近更新 更多