简体   繁体   English

为什么不能在列表推导式中解压列表?

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

Starred expressions raise SyntaxError when used in list or generator comprehension.在列表或生成器理解中使用时,带星号的表达式会引发SyntaxError

I'm curious about the reason behind this;我很好奇这背后的原因; is it an implementation choice or there are technical constraints that would prevent this operation?它是一种实现选择还是存在阻止此操作的技术限制?

I've found a lot about the contexts that don't allow for unpacking iterables but nothing about why.我发现了很多关于不允许解包迭代的上下文,但没有说明原因。

Example:例子:

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

I thought maybe I could use this to get [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5] as a result, but it raises我想也许我可以用它来得到[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]结果,但它提高了

SyntaxError("Iterable unpacking cannot be used in comprehension") SyntaxError("可迭代解包不能用于理解中")

This was proposed in PEP 448 -- Additional Unpacking Generalizations but ultimately not accepted due to concerns about readability:这是在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: [...]此 PEP 的早期迭代允许将列表、集合和字典推导式中的运算符解包为容器可迭代对象上的展平运算符:[...]
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.为了不损害 PEP 中争议较少的方面,提案的其余部分没有接受这一点。

Notably, the possibility to add this at a later point has not been ruled out.值得注意的是,不排除稍后添加此内容的可能性。

This PEP does not include unpacking operators inside list, set and dictionary comprehensions although this has not been ruled out for future proposals.此 PEP 不包括列表、集合和字典推导式中的解包运算符,尽管这在未来的提案中并未被排除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM