This question描述了如何使用列表推导来展平嵌套结构,如下所示:
[leaf for tree in forest for leaf in tree]
正如John Mee在评论中提到的那样,如果for
陈述的顺序被颠倒,这将更加清楚,如下所示:
[leaf for leaf in tree for tree in forest]
为什么Python的列表推导中的循环按此顺序解释?
答案 0 :(得分:5)
这个想法是模仿嵌套的for
循环。
[x for y in z for x in y]
的组织顺序与
相同for y in z:
for x in y:
yield x
中提到了这一点
表单
[... for x... for y...]
嵌套,最后一个索引变化最快,就像嵌套for循环一样。
答案 1 :(得分:2)
因为第一个更好地映射到它代表的for循环代码
[leaf *for tree in forest for leaf in tree*]
|
V
for tree in forest:
for leaf in tree:
|
V
expected result
而第二个在这个意义上是无效的
[leaf *for leaf in tree for tree in forest*]
|
V
for leaf in tree:
for tree in forest:
|
V
???