【问题标题】:Why does a python "in" statement evaluate this way? [duplicate]为什么 python "in" 语句以这种方式评估? [复制]
【发布时间】:2020-05-27 02:10:19
【问题描述】:

抱歉,我想不出一个更具描述性的标题。这不是非常重要,而是我发现的 python 3.8 中的一个奇怪的怪癖(至少),我认为我不能是唯一注意到这一点的人,并且可能有一个合理的解释:

>>> 'foo' in 'foobar' == True
False

反之亦然:

>>> True == 'foo' in 'foobar'
False

但是,从逻辑上讲,我认为这应该是正确的,因为

>>> 'foo' in 'foobar'
True
>>> True == True
True

我假设这是某种操作顺序错误,但是当我尝试对其进行分组时,我得到了

>>> ('foo' in 'foobar') == True
True
>>> 'foo' in ('foobar' == True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: argument of type 'bool' is not iterable

此时我主要是真的很好奇,如果有人能解释这一点,那就太好了!

【问题讨论】:

    标签: python python-3.x logical-operators


    【解决方案1】:

    因为operator chaining,表达式等价于:

    ('foo' in 'foobar') and ('foobar' == True)
    

    因为'foobar' == TrueFalse,所以整个表达式是False

    【讨论】:

    • 看起来完全正确。您还可以尝试评估 'foo' in 'foobar' in 'foobarbaz' (True),而无论以哪种方式添加括号都会导致类型错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多