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

What#39;s the meaning of quot;(1,) == 1,quot; in Python?(“(1,) == 1,是什么意思?在 Python 中?)
本文介绍了“(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())
)])

这篇关于“(1,) == 1,"是什么意思?在 Python 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)