Explanation of how nested list comprehension works?

前端 未结 8 1236
情书的邮戳
情书的邮戳 2020-11-22 02:06

I have no problem for understanding this:

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

I thought that was all, but then I found this snippet:



        
8条回答
  •  花落未央
    2020-11-22 02:39

    Ah, the incomprehensible "nested" comprehensions. Loops unroll in the same order as in the comprehension.

    [leaf for branch in tree for leaf in branch]
    

    It helps to think of it like this.

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

    The PEP202 asserts this syntax with "the last index varying fastest" is "the Right One", notably without an explanation of why.

提交回复
热议问题