matrix_a = [[3, 6], 
            [4, 9]]
matrix_b = [[7, 2], 
            [8, 3]]

 

 

1. 행렬 a를 행으로 자른다.

for row in matrix_a :
    print('row of a :',row)
row of a : [3, 6]
row of a : [4, 9]

 

 

2. 행렬 b를 열로 자른다.

for col in  zip(*matrix_b) :
    print('colum of b :',col)

※ 리스트로 묶여있는 행렬을 *로 풀어서 zip을 해야 열로 묶인다.

colum of b :  (7, 8)
colum of b :  (2, 3)

 

 

3. 행렬 a의 행과 행렬 b의 열에서 곱할 요소끼리 zip으로 묶어준다.

zip_result = [zip(row, col) 
              for col in zip(*matrix_b)
              for row in matrix_a]
for a,b in zip_result:
    print(a,b)
(3, 7) (6, 8)
(4, 7) (9, 8)
(3, 2) (6, 3)
(4, 2) (9, 3)

 

 

4. 묶여있는 요소끼리 곱하고 합을 구한다. 

result = [ [sum(a*b for a,b in zip(row, col)) 
          for col in zip(*matrix_b) ]
          for row in matrix_a]
print(result)

※  [sum(a*b for a,b in zip(row, col)) for col in zip(*matrix_b) ]  : 각 행을 리스트로 묶으려고 대괄호를 씌웠다.

[[69, 24], [100, 35]]

 

+ Recent posts