Explanation of how nested list comprehension works?

前端 未结 8 1219
情书的邮戳
情书的邮戳 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:35

    Here is how I best remember it: (pseudocode, but has this type of pattern)

    [(x,y,z) (loop 1) (loop 2) (loop 3)]
    

    where the right most loop (loop 3) is the inner most loop.

    [(x,y,z)    for x in range(3)    for y in range(3)    for z in range(3)]
    

    has the structure as:

    for x in range(3):
        for y in range(3):
            for z in range(3):
                print((x,y,z))
    

    Edit I wanted to add another pattern:

    [(result) (loop 1) (loop 2) (loop 3) (condition)]
    

    Ex:

    [(x,y,z)    for x in range(3)    for y in range(3)    for z in range(3)    if x == y == z]
    

    Has this type of structure:

    for x in range(3):
        for y in range(3):
            for z in range(3):
                if x == y == z:
                    print((x,y,z))
    
    
    
    

提交回复
热议问题