为什么无法在列表理解中解包列表?

Why is it not possible to unpack lists inside a list comprehension?

加星标的表达式在列表或生成器理解中使用时会引发 SyntaxError

我很好奇这背后的原因;这是一个实施选择还是存在阻止此操作的技术限制?

我发现了很多关于不允许解包可迭代对象的上下文,但没有找到原因。

示例:

lis = [1, 2, 3, 4, 5]
listcomp = [*lis for i in range(3)]

我想也许我可以用它来获得 [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5] 结果,但它引发了

SyntaxError("Iterable unpacking cannot be used in comprehension")

这是在 PEP 448 -- Additional Unpacking Generalizations 中提出的,但由于对可读性的担忧最终没有被接受:

Earlier iterations of this PEP allowed unpacking operators inside list, set, and dictionary comprehensions as a flattening operator over iterables of containers: [...]
This was met with a mix of strong concerns about readability and mild support. In order not to disadvantage the less controversial aspects of the PEP, this was not accepted with the rest of the proposal.

值得注意的是,不排除稍后添加此功能的可能性。

This PEP does not include unpacking operators inside list, set and dictionary comprehensions although this has not been ruled out for future proposals.