Explanation of how nested list comprehension works?

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

    if a = [[1,2],[3,4],[5,6]], then if we unroll that list comp, we get:

          +----------------a------------------+ 
          | +--xs---+ , +--xs---+ , +--xs---+ | for xs in a
          | | x , x |   | x , x |   | x , x | | for x in xs
    a  =  [ [ 1 , 2 ] , [ 3 , 4 ] , [ 5 , 6 ] ]
    b  =  [ x for xs in a for x in xs ] == [1,2,3,4,5,6] #a list of just the "x"s
    

提交回复
热议问题