简体   繁体   中英

How do nested list comprehensions work in python?

I am trying to understand list comprehension by deconstructing it. Suppose I have a matrix defined as a list of lists. ( Yes I know about numpy this is not about doing this in a simple efficient way. This is about understanding.) and a scalar

A = [[1, 2, 3],
     [2, 3, 6],
     [3, 4, 12]]

s = 7

As I discovered elsewhere, I can define a list comprehension to perform scalar multiplication.

def ScalarMult(A,s):
    return [[s*i for i in row] for row in A]

As = ScalarMult(A,s)
print('As = ', As)

and it returns

As = [[7, 14, 14], [14, 21, 42], [21, 28, 84]]

a nested list, which is what I want but how does this work?

If I write

def ScalarMult(A,s):
    As = []
    for row in A:
        for i in row:
            As.append(s*i)
    return As

this returns

As = [7, 14, 14, 14, 21, 42, 21, 28, 84]

a flattened list, which is not what I want. How can I write

[[s*i for i in row] for row in A]

as nested for loops and have it return a nested list and see plainly what it is doing with respect to this 3X3 matrix? And of course, I would like to define a function such as ScalarMult which works for matrices of any size.

You can write it like so:

def ScalarMult(A,s):
    As = []
    for row in A:
        Arow = []
        for i in row:
            Arow.append(s*i)
        As.append(Arow)
    return As

Taking this one step further gives:

def ScalarMult(A,s):
    As = []
    for row in A:
        As.append([s*i for i in row])
    return As

Taking it two steps further gives:

def ScalarMult(A,s):
    As = [[s*i for i in row] for row in A]
    return As

(ie what you started with.)

Hope this makes things clearer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM