Python 元组赋值和条件语句检查

2022-01-20 00:00:00 python python-2.7 tuples if-statement

问题描述

所以我偶然发现了 python 中元组的一种特殊行为,我想知道它是否有特定的原因发生.

So I stumbled into a particular behaviour of tuples in python that I was wondering if there is a particular reason for it happening.

虽然我们完全有能力将元组分配给变量,但无需明确地将其括在括号中:

While we are perfectly capable of assigning a tuple to a variable without explicitely enclosing it in parentheses:

>>> foo_bar_tuple = "foo","bar"
>>> 

我们无法打印或检查条件 if 语句包含的变量以前方式的元组(没有明确输入括号):

we are not able to print or check in a conditional if statement the variable containing the tuple in the previous fashion (without explicitely typing the parentheses):

>>> print foo_bar_tuple == "foo","bar"
False bar

>>> if foo_bar_tuple == "foo","bar": pass
SyntaxError: invalid syntax
>>> 

>>> print foo_bar_tuple == ("foo","bar")
True
>>> 

>>> if foo_bar_tuple == ("foo","bar"): pass
>>>

有人知道为什么吗?在此先感谢,虽然我没有找到任何类似的主题,但如果您认为这可能是重复的,请通知我.干杯,亚历克斯

Does anyone why? Thanks in advance and although I didn't find any similar topic please inform me if you think it is a possible dublicate. Cheers, Alex


解决方案

这是因为逗号分隔的表达式在整个逗号分隔的元组(Python语法术语中的表达式列表")之前计算.因此,当您执行 foo_bar_tuple=="foo", "bar" 时,会被解释为 (foo_bar_tuple=="foo"), "bar".文档中描述了这种行为.

It's because the expressions separated by commas are evaluated before the whole comma-separated tuple (which is an "expression list" in the terminology of the Python grammar). So when you do foo_bar_tuple=="foo", "bar", that is interpreted as (foo_bar_tuple=="foo"), "bar". This behavior is described in the documentation.

如果你自己写这样一个表达式你可以看到这个:

You can see this if you just write such an expression by itself:

>>> 1, 2 == 1, 2  # interpreted as "1, (2==1), 2"
(1, False, 2)

无括号元组的语法错误是因为无括号元组不是 Python 语法中的原子",这意味着它作为 if 条件的唯一内容无效.(您可以通过跟踪语法自行验证.)

The SyntaxError for the unparenthesized tuple is because an unparenthesized tuple is not an "atom" in the Python grammar, which means it's not valid as the sole content of an if condition. (You can verify this for yourself by tracing around the grammar.)

相关文章