Python - Using list comprehensions to combine values of multiple matrixes

Introduction

You can use list comprehensions to combine values of multiple matrixes.

The following first builds a flat list that contains the result of multiplying the matrixes pairwise.

And then builds a nested list structure having the same values by nesting list comprehensions again:

Demo

M = [[1, 2, 3], 
     [4, 5, 6], # from   ww w .  j a  v  a2 s .co m
     [7, 8, 9]] 

N = [[2, 2, 2], 
     [3, 3, 3], 
     [4, 4, 4]] 
d = [M[row][col] * N[row][col] for row in range(3) for col in range(3)] 
print(d)

d= [[M[row][col] * N[row][col] for col in range(3)] for row in range(3)] 

print(d)

Result

Related Topic