一尘不染

Python-嵌套列表理解如何工作的解释?

python

我对此毫无疑问:

a = [1,2,3,4]
b = [x for x in a]

我以为是全部,但是后来我发现了以下片段:

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],有人可以解释它的工作原理吗?


阅读 331

收藏
2020-02-13

共1个答案

一尘不染

难以理解的“嵌套”理解。循环以与理解相同的顺序展开。

[leaf for branch in tree for leaf in branch]

这样有助于你进行思考。

for branch in tree:
    for leaf in branch:
        yield leaf
2020-02-13