元组什么时候需要括号? [英] When are parentheses required around a tuple?

查看:95
本文介绍了元组什么时候需要括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在需要或不需要用括号括起来的元组时,是否有精确定义的引用?

这是一个最近让我感到惊讶的例子:

<预><代码>>>>d = {}>>>d[0,] = '土豆'>>>如果为 0,则在 d 中:文件<stdin>",第 1 行如果为 0,则在 d 中:^语法错误:无效语法

解决方案

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

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

例如if语句的语法如下:

if_stmt ::= "if" 表达式 ":" 套件(elif"表达式:"套件)*[其他":"套件]

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

for_stmt ::= "for" target_list "in" expression_list ":" suite[其他":"套件]

因此允许以下内容:

 for x in 1, 2, 3:打印(x)

Is there a reference somewhere defining precisely when enclosing tuples with parentheses is or is not required?

Here is an example that surprised me recently:

>>> d = {}
>>> d[0,] = 'potato'
>>> if 0, in d:
  File "<stdin>", line 1
    if 0, in d:
        ^
SyntaxError: invalid syntax

解决方案

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.

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.

For example, the grammar of the if statement is as follows:

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

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]

So the following is allowed:

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

这篇关于元组什么时候需要括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆