为什么Python的列表理解循环顺序向后? [英] Why is Python's list comprehension loop order backwards?

查看:76
本文介绍了为什么Python的列表理解循环顺序向后?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

>>> my_list = [[[[1, 2, 3], [4, 5, 6], ]]]
>>> [a for d in my_list for c in d for b in c for a in b]
[1, 2, 3, 4, 5, 6]

等同于

>>> my_list = [[[[1, 2, 3], [4, 5, 6], ]]]
>>> new_list = []
>>> for d in my_list:
...     for c in d:
...         for b in c:
...             for a in b:
...                 new_list.append(a)
... print(new_list):
[1, 2, 3, 4, 5, 6]

从左向右读取时,此语法似乎是向后的.根据 PEP 202 ,"[... for x... for y...]表格嵌套,最后一个索引变化最快,就像嵌套的循环一样."是正确的人".

This syntax seems backwards when read from left-to-right. According to PEP 202, "The form [... for x... for y...] nests, with the last index varying fastest, just like nested for loops." is "the Right One."

似乎选择了这个顺序(从左到右,对应于从内到外嵌套的for循环),因为这是嵌套的for循环的写入顺序.

It seems that this order (of left-to-right corresponding to outer-to-inner nested for loops) was chosen because that is the order in which nested for loops are written.

但是,由于列表理解的表达式部分(在上面的示例中为a)对应于嵌套循环最内层的表达式(在上面的示例中为new_list.append(a)),因此似乎我认为,最接近此表达式的for _ in _在两种情况下都应相同,即应为for a in b并且向外:

However, since the expression part of the list comprehension (a in the above example), corresponds to the expression at the inner-most part of the nested loops (new_list.append(a) in the above example), it seems to me that the for _ in _ closest to this expression should be the same in both cases, i.e. it should be for a in b and on outwards:

>>> my_list = [[[[1, 2, 3], [4, 5, 6], ]]]
>>> [a for a in b for b in c for c in d for d in my_list]
NameError: name 'b' is not defined

这样可以使变化最快的循环最接近动作.这也使其更易于以逻辑上逐步的方式从左向右读取.

so that the fastest-changing loop is closest to the action, so-to-speak. This also lends itself to being read from left-to-right in more logically stepwise fashion.

这是用户之间的共同情感吗?还是有人对当前的语法实现为何真正是正确的人"有很好的反驳?

Is this a common sentiment among users? or does anyone have a good counter-argument as to why the current syntax implementation really is "the Right One"?

推荐答案

考虑:

[leaf for branch in tree for leaf in branch]

它的展开方式如下:

for branch in tree:
    for leaf in branch:
        yield leaf

如果我们用另一种方式写

If we write it the other way

[leaf for leaf in branch for branch in tree]

在某种程度上用通俗易懂的英语表达可能更有意义,但可能的反驳是此处使用的分支"名称尚未定义(尚未定义).

It might make more sense in plain English on some level, but a possible counter-argument is that here the name "branch" is used without being (yet) defined.

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

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