且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

元组周围什么时候需要括号?

更新时间:2022-06-01 09:16:07

使用逗号标记创建元组的表达式组合称为 expression_list.运算符优先级的规则不包括表达式列表;这是因为表达式列表本身不是表达式;括在括号中时它们成为表达式.

The combining of expressions to create a tuple using the comma token is termed an expression_list. The rules of operator precedence do not cover expression lists; this is because expression lists are not themselves expressions; they become expressions when enclosed in parentheses.

因此,在 Python 中语言语法明确允许的任何地方都允许使用未封闭的 expression_list,但 不允许其中 expression 为这是必需的.

So, an unenclosed expression_list is allowed anywhere in Python that it is specifically allowed by the language grammar, but not where an expression as such is required.

例如if语句的语法如下:

if_stmt ::=  "if" expression ":" suite
             ( "elif" expression ":" suite )*
             ["else" ":" suite]

因为引用了产生式 expression,所以不允许未封闭的 expression_list 作为 if 语句的主题.但是,for 语句 接受 expression_list:

Because the production expression is referenced, unenclosed expression_lists are not allowed as the subject of the if statement. However, the for statement accepts an expression_list:

for_stmt ::=  "for" target_list "in" expression_list ":" suite
              ["else" ":" suite]

所以以下是允许的:

for x in 1, 2, 3:
    print(x)