Explanation of how nested list comprehension works?

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

    This is an example of a nested comprehension. Think of a = [[1,2],[3,4],[5,6]] as a 3 by 2 matrix (matrix= [[1,2],[3,4],[5,6]]).

           ______
    row 1 |1 | 2 |
           ______
    row 2 |3 | 4 |
           ______
    row 3 |5 | 6 |
           ______
    

    The list comprehension you see is another way to get all the elements from this matrix into a list.

    I will try to explain this using different variables which will hopefully make more sense.

    b = [element for row in matrix for element in row]
    

    The first for loop iterates over the rows inside the matrix ie [1,2],[3,4],[5,6]. The second for loop iterates over each element in the list of 2 elements.

    I have written a small article on List Comprehension on my website http://programmathics.com/programming/python/python-list-comprehension-tutorial/ which actually covered a very similar scenario to this question. I also give some other examples and explanations of python list comprehension.

    Disclaimer: I am the creator of that website.

提交回复
热议问题