“(1,) == 1,"是什么意思?在 Python 中?
问题描述
我正在测试元组结构,发现使用 ==
运算符时很奇怪:
I'm testing the tuple structure, and I found it's strange when I use the ==
operator like:
>>> (1,) == 1,
Out: (False,)
当我将这两个表达式赋值给一个变量时,结果为真:
When I assign these two expressions to a variable, the result is true:
>>> a = (1,)
>>> b = 1,
>>> a==b
Out: True
这个问题不同于我的 Python tuple trailing comma syntax rule看法.我问 ==
运算符之间的表达式组.
This questions is different from Python tuple trailing comma syntax rule in my view. I ask the group of expressions between ==
operator.
解决方案
其他答案已经向您表明该行为是由于运算符优先级引起的,如文档 这里.
Other answers have already shown you that the behaviour is due to operator precedence, as documented here.
下次您遇到类似的问题时,我将向您展示如何自己找到答案.您可以使用 ast
解构表达式的解析方式模块:
I'm going to show you how to find the answer yourself next time you have a question similar to this. You can deconstruct how the expression parses using the ast
module:
>>> import ast
>>> source_code = '(1,) == 1,'
>>> print(ast.dump(ast.parse(source_code), annotate_fields=False))
Module([Expr(Tuple([Compare(Tuple([Num(1)], Load()), [Eq()], [Num(1)])], Load()))])
从这里我们可以看到代码被解析正如蒂姆·彼得斯解释的那样:
From this we can see that the code gets parsed as Tim Peters explained:
Module([Expr(
Tuple([
Compare(
Tuple([Num(1)], Load()),
[Eq()],
[Num(1)]
)
], Load())
)])
相关文章