Converting List Comprehensions to For Loops in Pyt

2019-02-27 02:34发布

问题:

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 loop. For example, how could I change this to a for loop:

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

In this example I have a list of lists, for my purposes a matrix, called outer_list which is a list of lists. The index value is the column number the outer iteration is at, from 0 to some number n. The list comprehension above returns the index'th column in the matrix, and assigns it to li as a list. How can I create a for loop that creates a list in this manner?

回答1:

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).



回答2:

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])


回答3:

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.



回答4:

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.