python - 为什么多个 `for`列表理解的顺序是这样的?

标签 python python-3.x syntax

我知道在嵌套列表理解中有多个 for 的正确方法如下(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]

但我的自然语言直觉强烈反对。我会(错误地)期望代码是:

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

错误的版本听起来几乎像英语,并且是从左到右的一条流中读取的。正确的版本需要一些嵌套阅读技巧,左右跳跃以包含含义。

为什么这个语法是这样的?为什么以这种方式构建语言?

最佳答案

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

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

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

如果您已经习惯了 排序,这就很自然了。

查看 very first discussions about the feature似乎有其他语言的排序先例。事实上,Haskell has the same ordering : 每个后续生成器都会改进前一个生成器的结果

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

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 .

关于python - 为什么多个 `for`列表理解的顺序是这样的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38321559/

相关文章:

python - 测量数据帧的负/正偏度

python - 如何在 A100 GPU 上使用 Pytorch (+ cuda)?

python - 当我在 selenium python 中获取 MP4 文件的 URL 时如何下载视频? (没有 URLLIB)

syntax - 来自ocaml的Nest Let语法

Python,使用for循环打印两列数字

python - 在 Python 中编辑 CSV 文件名以附加到当前文件名

python-3.x - 将代码链接打印到 PyCharm 控制台

python - 如何使用选择器获取父标签?

C++ 私有(private)复制构造函数问题

javascript - jQuery 链接以创建连接字符串