Python tuple assignment and checking in conditional statements(Python 元组赋值和条件语句检查)
问题描述
所以我偶然发现了 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.)
这篇关于Python 元组赋值和条件语句检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python 元组赋值和条件语句检查


- 我如何卸载 PyTorch? 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01