元组何时需要括号?

是否有地方需要精确定义引用,何时需要用括号将元组括起来?


这是一个最近令我惊讶的例子:


>>> d = {}

>>> d[0,] = 'potato'

>>> if 0, in d:

  File "<stdin>", line 1

    if 0, in d:

        ^

SyntaxError: invalid syntax


繁星点点滴滴
浏览 393回答 3
3回答

白衣非少年

使用逗号标记将表达式的组合以创建元组称为expression_list。运算符优先级规则不涵盖表达式列表;这是因为表达式列表本身不是表达式;当用括号括起来时,它们成为表达式。所以,一个未封闭expression_list在Python允许任何地方,它是具体由语言的语法允许的,但不是在那里的expression,需要这样。例如,if语句的语法如下:if_stmt ::=&nbsp; "if" expression ":" suite&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;( "elif" expression ":" suite )*&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;["else" ":" suite]因为expression引用了生产,expression_list所以不允许将未封闭的s作为if语句的主题。但是,for语句接受expression_list:for_stmt ::=&nbsp; "for" target_list "in" expression_list ":" suite&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ["else" ":" suite]因此,允许以下内容:for x in 1, 2, 3:&nbsp; &nbsp; print(x)

婷婷同学_

在允许使用该expression_list术语的任何地方,都无需使用括号。该if语句需要一个expression,不支持expression_list。允许的语法示例expression_list:该return声明yield 表达作业 (包括扩充作业)该for声明。掌握Expressions,Simple和Compound语句文档expression_list将告诉您expression_listPython语法中使用的所有位置。

三国纷争

当您想避免歧义时,也需要加上括号。以下是两个不同的表达式...仅仅因为某些东西是“表达式列表”,不会导致您可能期望的表达式列表:)(1, 2, 3) + (4, 5) # results in (1, 2, 3, 4, 5) because + does sequence.extend on the tuples1, 2, 3 + 4, 5&nbsp; &nbsp; &nbsp;# this results in (1, 2, 7, 5) because + adds the elements, since there were no parentheses to protect the separate tuples
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python