为什么列表理解中的元组需要括号? [英] Why do tuples in a list comprehension need parentheses?

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

问题描述

众所周知,元组不是用括号定义的,而是逗号. 从文档引用:

It is well known that tuples are not defined by parentheses, but commas. Quote from documentation:

元组由多个用逗号分隔的值组成

A tuple consists of a number of values separated by commas

因此:

myVar1 = 'a', 'b', 'c'
type(myVar1)
# Result:
<type 'tuple'>

另一个引人注目的例子是这样:

Another striking example is this:

myVar2 = ('a')
type(myVar2)
# Result:
<type 'str'>  

myVar3 = ('a',)
type(myVar3)
# Result:
<type 'tuple'>

即使单元素元组也需要逗号,并且始终使用括号只是为了避免混淆. 我的问题是:为什么我们不能在列表理解中省略数组的括号?例如:

Even the single-element tuple needs a comma, and parentheses are always used just to avoid confusion. My question is: Why can't we omit parentheses of arrays in a list comprehension? For example:

myList1 = ['a', 'b']
myList2 = ['c', 'd']

print([(v1,v2) for v1 in myList1 for v2 in myList2])
# Works, result:
[('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd')]

print([v1,v2 for v1 in myList1 for v2 in myList2])
# Does not work, result:
SyntaxError: invalid syntax

接下来的循环中,第二个列表理解不是语法糖吗?

Isn't the second list comprehension just syntactic sugar for the following loop, which does work?

myTuples = []
for v1 in myList1:
    for v2 in myList2:
        myTuple = v1,v2
        myTuples.append(myTuple)
print myTuples
# Result:
[('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd')]

推荐答案

Python的语法为 LL (1),表示它在解析时仅向前看一个符号.

Python's grammar is LL(1), meaning that it only looks ahead one symbol when parsing.

[(v1, v2) for v1 in myList1 for v2 in myList2]

在这里,解析器会看到类似这样的内容.

Here, the parser sees something like this.

[ # An opening bracket; must be some kind of list
[( # Okay, so a list containing some value in parentheses
[(v1
[(v1,
[(v1, v2
[(v1, v2)
[(v1, v2) for # Alright, list comprehension

但是,没有括号,它必须更早地做出决定.

However, without the parentheses, it has to make a decision earlier on.

[v1, v2 for v1 in myList1 for v2 in myList2]

[ # List-ish thing
[v1 # List containing a value; alright
[v1, # List containing at least two values
[v1, v2 # Here's the second value
[v1, v2 for # Wait, what?

众所周知,回溯的解析器往往很慢,因此LL(1)解析器不会回溯.因此,模棱两可的语法是禁止的.

A parser which backtracks tends to be notoriously slow, so LL(1) parsers do not backtrack. Thus, the ambiguous syntax is forbidden.

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

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