为什么([1,0]中的1 = = True)评估为False? [英] Why does (1 in [1,0] == True) evaluate to False?

查看:98
本文介绍了为什么([1,0]中的1 = = True)评估为False?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我查看的答案时,我发现自己不明白自己的答案.

When I was looking at answers to this question, I found I didn't understand my own answer.

我不太了解如何对此进行解析.为什么第二个示例返回False?

I don't really understand how this is being parsed. Why does the second example return False?

>>> 1 in [1,0]             # This is expected
True
>>> 1 in [1,0] == True     # This is strange
False
>>> (1 in [1,0]) == True   # This is what I wanted it to be
True
>>> 1 in ([1,0] == True)   # But it's not just a precedence issue!
                           # It did not raise an exception on the second example.

Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    1 in ([1,0] == True)
TypeError: argument of type 'bool' is not iterable

感谢您的帮助.我想我一定会错过一些非常明显的东西.

Thanks for any help. I think I must be missing something really obvious.

我认为这与链接的副本完全不同:

I think this is subtly different to the linked duplicate:

为什么表达式0< 0 == 0在Python中返回False吗?.

两个问题都与人类对表达的理解有关.在我看来,似乎有两种评估表达方式的方法.当然,两者都不正确,但是在我的示例中,最后的解释是不可能的.

Both questions are to do with human comprehension of the expression. There seemed to be two ways (to my mind) of evaluating the expression. Of course neither were correct, but in my example, the last interpretation is impossible.

看看0 < 0 == 0,您可以想象每一个被评估的部分都可以表达为有意义:

Looking at 0 < 0 == 0 you could imagine each half being evaluated and making sense as an expression:

>>> (0 < 0) == 0
True
>>> 0 < (0 == 0)
True

因此该链接回答了为什么它评估False的原因:

So the link answers why this evaluates False:

>>> 0 < 0 == 0
False

但是对于我的示例,1 in ([1,0] == True)作为表达式没有意义,因此,除了存在两种(公认错误的)可能的解释之外,似乎只有一种可能:

But with my example 1 in ([1,0] == True) doesn't make sense as an expression, so instead of there being two (admittedly wrong) possible interpretations, only one seems possible:

>>> (1 in [1,0]) == True

推荐答案

Python实际上在这里应用了比较运算符链接.表达式被翻译为

Python actually applies comparison operator chaining here. The expression is translated to

(1 in [1, 0]) and ([1, 0] == True)

显然是False.

类似的表达式也是如此

a < b < c

翻译成

(a < b) and (b < c)

(无需两次评估b).

有关详细信息,请参见 Python语言文档.

See the Python language documentation for further details.

这篇关于为什么([1,0]中的1 = = True)评估为False?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆