为什么在Python中'=='在'in'之前?

2024-04-19 05:52:07 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的代码输出False,根据Python的操作顺序,它应该输出True(顺序应该是->;==,而不是相反)。为什么==先进来?在

y = "33"
"3" in y == True

输出

^{pr2}$

Tags: 代码ingtfalsetrue顺序pr2
2条回答

在python中,比较、成员身份测试和身份测试都具有相同的优先级。 检查成员资格的关键字in返回bool,不需要与第二个bool进行额外比较。但是,可以将表达式分组如下。。。在

y = "33"

("3" in y) == True

现有的答案给出了一些有用的建议,即不应该将布尔值与True进行比较,因为这是多余的。然而,没有一个答案真正回答了根问题:“为什么"3" in y == True的计算结果是False?”。在

这个问题在一篇评论中得到了回答胡安帕.阿里维拉加公司名称:

Also, this is an instance of operator chaining, since == and in both count as comparison operators. So this is evaluated as ('3' in y) and (y == True)

在Python中,比较运算符可以链接到上。例如,如果您想检查abc和{}是否在增加,可以编写a < b < c < d,而不是{}。类似地,您可以检查它们是否都与a == b == c == d相等。在

Python文档here中描述了链式比较:

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

相关问题 更多 >