Python中“(1,)== 1”是什么意思?

问题:Python中“(1,)== 1”是什么意思?

我正在测试元组结构,当我==像这样使用运算符时发现它很奇怪:

>>>  (1,) == 1,
Out: (False,)

当我将这两个表达式分配给变量时,结果为true:

>>> a = (1,)
>>> b = 1,
>>> a==b
Out: True

在我看来,这个问题与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

This questions is different from Python tuple trailing comma syntax rule in my view. I ask the group of expressions between == operator.


回答 0

其他答案已经向您显示该行为是由于运算符的优先级所致,如此处所述

下次您遇到类似问题时,我将向您展示如何找到答案。您可以使用以下ast模块来解构表达式的解析方式:

>>> 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()))])

从中我们可以看到代码已按照Tim Peters的解释进行了解析:

Module([Expr(
    Tuple([
        Compare(
            Tuple([Num(1)], Load()), 
            [Eq()], 
            [Num(1)]
        )
    ], Load())
)])

Other answers have already shown you that the behaviour is due to operator precedence, as documented here.

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())
)])

回答 1

这只是运算符的优先级。你的第一个

(1,) == 1,

像这样的团体:

((1,) == 1),

因此,根据将一个元素的元组1,与整数1进行相等性比较的结果来构建一个具有单个元素的元组False,

This is just operator precedence. Your first

(1,) == 1,

groups like so:

((1,) == 1),

so builds a tuple with a single element from the result of comparing the one-element tuple 1, to the integer 1 for equality They’re not equal, so you get the 1-tuple False, for a result.


回答 2

当你做

>>> (1,) == 1,

它通过将元 (1,)整数进行比较并返回来生成一个元组False

相反,当您分配变量时,两个相等的元组会相互比较。

你可以试试:

>>> x = 1,
>>> x
(1,)

When you do

>>> (1,) == 1,

it builds a tuple with the result from comparing the tuple (1,) with an integer and thus returning False.

Instead when you assign to variables, the two equal tuples are compared with each other.

You can try:

>>> x = 1,
>>> x
(1,)