嵌套列表理解如何工作的解释? [英] Explanation of how nested list comprehension works?
本文介绍了嵌套列表理解如何工作的解释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对此毫无疑问:
a = [1,2,3,4]
b = [x for x in a]
我以为是全部,但是后来我发现了这个片段:
I thought that was all, but then I found this snippet:
a = [[1,2],[3,4],[5,6]]
b = [x for xs in a for x in xs]
哪个是b = [1,2,3,4,5,6]
.问题是我很难理解[x for xs in a for x in xs]
中的语法,谁能解释它的工作原理吗?
Which makes b = [1,2,3,4,5,6]
. The problem is I'm having troubles to understand the syntax in [x for xs in a for x in xs]
, Could anyone explain how it works?
推荐答案
啊,难以理解的嵌套"理解.循环以与理解相同的顺序展开.
Ah, the incomprehensible "nested" comprehensions. Loops unroll in the same order as in the comprehension.
[leaf for branch in tree for leaf in branch]
这样有助于思考它.
for branch in tree:
for leaf in branch:
yield leaf
PEP202 断言这种语法具有最近的索引变化最快"是正确的人",尤其是在没有解释为什么的情况下.
The PEP202 asserts this syntax with "the last index varying fastest" is "the Right One", notably without an explanation of why.
这篇关于嵌套列表理解如何工作的解释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文