众所周知,元组不是由括号定义的,而是由逗号定义的Quote from documentation:
A tuple consists of a number of values separated by commas
因此:
myVar1 = 'a', 'b', 'c'
type(myVar1)
# Result:
<type 'tuple'>
另一个显著的例子是:
myVar2 = ('a')
type(myVar2)
# Result:
<type 'str'>
myVar3 = ('a',)
type(myVar3)
# Result:
<type 'tuple'>
即使是单元素元组也需要逗号,并且总是使用括号来避免混淆我的问题是:为什么不能在列表中省略数组的括号?例如:
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
第二个列表理解不就是下面这个循环的语法糖吗?这个循环确实有效
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')]
不存在引起此限制的解析器问题。与Silvio Mayolo的回答相反,LL(1)解析器可以很好地解析无括号语法。在原始列表理解补丁的早期版本中,括号是可选的;它们只是为了使含义更清楚而被强制执行
引用2000年Guido van Rossum的话,在一篇response中,有人担心
[x, y for ...]
会导致解析器问题另请参见线程中的next response,Greg Ewing在其中运行
在列表理解补丁的早期版本上,它工作得很好
当我觉得有点太尖刻时,我想出了一个理由
它开始将表达式解析为list/set/tuple,并期望得到一个
,
而不是一个for
标记例如:
标记如下:
Python的语法是LL(1),这意味着它在解析时只向前看一个符号
在这里,解析器看到如下内容
然而,如果没有括号,它必须在早些时候作出决定
回溯的解析器往往非常慢,因此LL(1)解析器不会回溯。因此,不明确的语法是被禁止的
相关问题 更多 >
编程相关推荐