为什么多个`for`列表理解的顺序是这样的? [英] Why is the order of multiple `for` list comprehension the way it is?

查看:48
本文介绍了为什么多个`for`列表理解的顺序是这样的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在嵌套列表理解中使用多个 for 的正确方法如下(Python 3):

I know the right way to have multiple for in a nested list comprehension is as follows (Python 3):

lista = [[[1,2],[3],[4,5,6]],[[7],[8,9]]]

flatlista = [i for k in lista for j in k for i in j]
# results with [1, 2, 3, 4, 5, 6, 7, 8, 9]

但我的自然语言本能强烈反对.我会(错误地)期望代码是:

But my natural language instincts strongly object. I would have (wrongly) expected the code to be:

flatlista = [i for i in j for j in k for k in lista]

错误的版本听起来几乎像英语,从左到右在一个流中阅读.正确的版本需要一些嵌套阅读技巧,左右跳过以包含含义.

The wrong version sounds almost like English and is read in one stream left to right. The correct version requires some nested reading skills skipping left and right to encompass the meaning.

为什么是这样的语法?为什么语言是这样构建的?

Why is this syntax as it is? Why was the language built this way?

推荐答案

因为PEP 202 -- List Comprehensions 将其设置为.然而,PEP 并没有完全说明原因,因为它是事后创建的;在创建 PEP 之前,甚至在创建 PEP 流程之前,就已经在开发列表上进行了讨论.

Because that's what PEP 202 -- List Comprehensions set it to. The PEP doesn't quite motivate why however, as it was created as an afterthought; the discussion had taken place on the development lists years before the PEP was created, or even the PEP process had been created.

首先,该顺序反映了您在 Python 代码中嵌套 for 循环和 if 语句的顺序:

First of all, the order mirrors the order you'd nest for loops and if statements in Python code:

for k in lista:
    for j in k:
        for i in j:

如果您已经习惯了那种排序,这将变得非常自然.

This makes it very natural if you are already used to that ordering.

查看 最初的讨论关于该功能 似乎有其他语言的订购先例.事实上,Haskell 具有相同的顺序:每个连续的生成器都会改进前一个生成器的结果.

Looking at the very first discussions about the feature there appears to be precedent in other languages for the ordering. And indeed, Haskell has the same ordering: each successive generator refines the results of the previous generator.

当然,在某些时候蒂姆·彼得斯(提案的发起人)表示今天使用的顺序对来说是显而易见的,请参阅这篇文章:

Certainly, at some point Tim Peters (the originator of the proposal) states that the order used today is obvious to him, see this post:

我已经多次将我建议的翻译发布到今天的 Python 中,意图是从字面上理解,而不是暗示性地理解.这窝for"循环最左边的最外面,所以钉住所有关于所有级别的排序语义.为什么这已经成为一个争论点水平超出我的范围.

I've posted my proposed translation into today's Python a few times already, with the intent that it be taken literally, not suggestively. This nests "for" loops with the leftmost outermost, so nails everything about the ordering semantics at all levels. Why that's become a debating point at all levels is beyond me .

这篇关于为什么多个`for`列表理解的顺序是这样的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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