Converting List Comprehensions to For Loops in Python

前端 未结 4 1801
轻奢々
轻奢々 2020-12-02 00:51

I understand the importance of list comprehensions, but do not understand their inner-workings, thus am not able to understand them in simpler terms such as I would a for lo

4条回答
  •  遥遥无期
    2020-12-02 01:55

    Your question seems to imply that this snippet is already inside of a for loop, like this:

    outer_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    
    for index in xrange(3):
        li = [row[index] for row in outer_list]
        print li
    

    which would output:

    [1, 4, 7]
    [2, 5, 8]
    [3, 6, 9]
    

    You could convert this to use only conventional for loops by nesting an inner loop inside of your outer loop:

    outer_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    
    for index in xrange(3):
        li = []                    # initial empty list
        for row in outer_list:     # our inner loop
            li.append(row[index])  # Build the list "li" iteratively
        print li
    

    If you are treating this nested list as a matrix, then what you describe is essentially taking the transpose of the matrix. You can do this entirely via list comprehensions as well:

    outer_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    
    transpose = [[row[i] for row in outer_list] for i in range(len(outer_list[0]))]
    
    print transpose
    

    which yields:

    [[1, 4, 7],
    [2, 5, 8],
    [3, 6, 9]]
    

    As shown in the official Python tutorial here.

    I've included the nested list comprehension example by way of completeness but a word to the wise: using nested list comprehensions generally makes code less comprehensible, not more. Just because you can doesn't mean you should.

提交回复
热议问题