【问题标题】:Weird behaviour of `not` operator with python list`not` 运算符与 python 列表的奇怪行为
【发布时间】:2020-01-20 21:09:46
【问题描述】:

当我尝试使用 python 的 not 运算符检查列表是否为空时,它的行为方式很奇怪。

我尝试使用not 运算符和一个列表来检查它是否为空。

>>> a = []
>>> not (a)
True
>>> not (a) == True
True
>>> not (a) == False
True
>>> True == False
False

not (a) == False 的预期输出应该是 False。

【问题讨论】:

    标签: python list conditional-statements


    【解决方案1】:

    这是按预期工作的。下面添加了括号以阐明这是如何执行的:

    not (a == True)
    # True
    not (a == False)
    # True
    

    一个空列表,布尔表达式中的a = []evaluates to False,但它不等于 FalseTrue。中间的表达式正在测试它是否等于FalseTrue,所以它们都等于False,而not FalseTrue

    你可以像下面这样添加括号来得到你所期望的:

    (not a) == True
    # True
    (not a) == False
    # False
    

    【讨论】:

    • 为了完整起见:您可以强制转换为 bool 以强制进行布尔评估。 bool([]) 返回False。所以:bool(a) == False 甚至 bool(a) is False 都是 True
    【解决方案2】:

    ==not 具有 higher precedencenot (a) == False 被解析为not (a == False)

    【讨论】:

      猜你喜欢
      • 2012-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-29
      • 1970-01-01
      • 2019-09-06
      • 2013-10-29
      相关资源
      最近更新 更多