Converting List Comprehensions to For Loops in Python

前端 未结 4 1788
轻奢々
轻奢々 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:38

    It's just a shorter way of expressing a list.

    li = [row[index] for row in outer_list]
    

    is equivalent to:

    li = []
    for row in outer_list:
        li.append(row[index])
    

    Once you get used to the syntax, it becomes a tidy way of creating lists (and other iterables).

    0 讨论(0)
  • 2020-12-02 01:40

    Assuming the outer iteration is for the index, this code can be effectively re-written as :

    for row in outer_list:
        li.append(row[index])
    

    Here you are iterating in the lists inside the outer_list. So, the first iteration would add the first list inside outer_list to li, then the second one is appended and so on.

    0 讨论(0)
  • 2020-12-02 01:51

    Question:

    How could I change this to a for loop?

    li = [row[index] for row in outer_list]
    

    Answer:

    li = []
    for row in outer_list:
       li.append(row[index])
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题