我知道在和 == 在 python 中具有相同的优先级。但奇怪的结果发生了[重复]

Posted

技术标签:

【中文标题】我知道在和 == 在 python 中具有相同的优先级。但奇怪的结果发生了[重复]【英文标题】:I knew in and == has same precedence in python. but strange result happens [duplicate] 【发布时间】:2021-10-09 16:31:04 【问题描述】:
number = 3
numbers = []
if number in numbers == False:
    numbers.append(number)

print(numbers)

我猜 numbers 有 3。但它什么都没有。

这是为什么呢??

【问题讨论】:

比较链使得number in numbers and numbers == False. 比较链docs.python.org/3/reference/expressions.html#comparisons 【参考方案1】:
number in numbers == False

是comparison operator chaining,相当于:

number in numbers and numbers == False

这类似于更明显的例子:

1 < a < 5
x == y == z

为了使您的测试按预期工作,您必须用括号标记优先级:

(number in numbers) == False

或者干脆使用推荐的:

number not in numbers

【讨论】:

以上是关于我知道在和 == 在 python 中具有相同的优先级。但奇怪的结果发生了[重复]的主要内容,如果未能解决你的问题,请参考以下文章