“((1,)== 1)"的含义是什么?在Python中? [英] What's the meaning of "(1,) == 1," in Python?

查看:402
本文介绍了“((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,)

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

When I assign these two expressions to a variable, the result is true:

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

此问题与我中的 Python元组尾随逗号语法规则不同看法.我问==运算符之间的表达式组.

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

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

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)"的含义是什么?在Python中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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