【问题标题】:Python Bool and int comparison and indexing on list with boolean valuesPython Bool 和 int 比较以及使用布尔值对列表进行索引
【发布时间】:2012-09-25 03:49:15
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: python list indexing boolean


    【解决方案1】:

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

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

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

    (由于历史原因,Bools 是整数。在 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.
    

    【讨论】:

    【解决方案2】:

    Python 使用 缺少布尔值,我们只使用整数,0 表示False,任何其他整数表示True。因此,当布尔值添加到语言中时,值FalseTrue 仍然可以被解释器视为整数值01,以帮助向后兼容。在内部,boolint 的子类。

    换句话说,以下等式是正确的:

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

    如你所见:

    >>> True * 3
    3
    

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

    【讨论】:

      【解决方案3】:

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

      Source.

      如您所见,False0True1

      【讨论】:

        【解决方案4】:

        Python 源文档没有直接提到当传递给if 语句时,所有非零整数都计算为True,而只有零计算为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(含)。

        【讨论】:

        • 问题是反过来的。列表索引从 Boolean 转换为 Int 但不是从 String 转换为 Int。
        • @line-o 这个问题刚刚问到“内部发生了什么”,我试图以一种对我来说有意义的方式来回答这个问题。不过,我确实很感谢大家的反对和反馈。
        猜你喜欢
        • 2015-06-30
        • 2016-02-16
        • 2020-06-04
        • 1970-01-01
        • 1970-01-01
        • 2020-08-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多