为什么使用列表推导式创建元组列表需要括号?

8

如在函数式编程HOWTO中所述,要使用列表推导创建元组列表,必须使用圆括号。 特别是,在以下引用中表达了这一点:

为避免在Python语法中引入歧义,如果表达式正在创建一个元组,则必须用圆括号括起来。

因此,例如:

[x, y for x in seq1 for y in seq2]  # This is a syntex error
[(x, y) for x in seq1 for y in seq2]  # This is a correct expression of list of tuples using list comprehension

在使用列表推导式表达元组列表时,强制使用括号可以避免什么样的歧义?

1
@Georgy:不幸的是,那个问题目前被接受的答案是错误的。(在找到其他证实之前,这就是我会猜测的,但仍然是错误的。) - user2357112
请参阅为什么列表推导中的元组需要括号?,该问题中@user2357112提到了错误的答案。 - John Kugelman
2个回答

9

经过大量的邮件列表查阅,我发现有一个非常明确的陈述,即解析器对此没有问题。括号是为了使含义更清晰而被强制使用的。以下是2000年Guido在python-dev邮件列表中的引用

Don't worry. Greg Ewing had no problem expressing this in Python's own grammar, which is about as restricted as parsers come. (It's LL(1), which is equivalent to pure recursive descent with one lookahead token, i.e. no backtracking.)

Here's Greg's grammar:

atom: ... | '[' [testlist [list_iter]] ']' | ...
  list_iter: list_for | list_if
  list_for: 'for' exprlist 'in' testlist [list_iter]
  list_if: 'if' test [list_iter]

Note that before, the list syntax was '[' [testlist] ']'. Let me explain it in different terms:

The parser parses a series comma-separated expressions. Previously, it was expecting ']' as the sole possible token following this. After the change, 'for' is another possible following token. This is no problem at all for any parser that knows how to parse matching parentheses!

If you'd rather not support [x, y for ...] because it's ambiguous (to the human reader, not to the parser!), we can change the grammar to something like:

'[' test [',' testlist | list_iter] ']'

(Note that | binds less than concatenation, and [...] means an optional part.)

另请参阅该线程的下一个回复,其中Greg Ewing进行了演示。

>>> seq = [1,2,3,4,5]
>>> [x, x*2 for x in seq]
[(1, 2), (2, 4), (3, 6), (4, 8), (5, 10)]

在早期版本的列表推导式补丁上,它能够正常工作。

-1

来自文档

正如您所看到的,输出的元组始终用括号括起来,以便正确解释嵌套元组;它们可以带或不带周围的括号进行输入,尽管通常无论如何都需要括号(如果元组是较大表达式的一部分)。无法为元组的各个项分配值,但可以创建包含可变对象(例如列表)的元组。

在列表推导中,元组嵌套在列表中。因此,它们必须用括号括起来。但是当它们没有被嵌套时,例如the_tuples = 'a','b','c',它们不是必需的,因为它们会自动被识别为元组。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接