我对此毫无疑问:
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],有人可以解释它的工作原理吗?
b = [1,2,3,4,5,6]
[x for xs in a for x in xs]
难以理解的“嵌套”理解。循环以与理解相同的顺序展开。
[leaf for branch in tree for leaf in branch]
这样有助于你进行思考。
for branch in tree: for leaf in branch: yield leaf