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

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

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

相关文档推荐

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中安全地调用随机文件上的类型?)