Python矩阵乘法变体 [英] Python Matrix Multiplication Variations

查看:83
本文介绍了Python矩阵乘法变体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚刚问了一个关于矩阵乘法的问题,可以在

just asked a question about multiplying matrices and that can be found here, I have one more question though about multiplying matrices. Say I have the following matrices:

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

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

我怎么能得到这样的结果:

How could I get a result like this:

[[1, 4, 9], [16, 25, 36], [49, 64, 81]]

...以便每个元素基本上都与另一个数组的单个对应元素相乘.有人知道怎么做吗?

...so that each element is basically being multiplied by the single corresponding element of the other array. Does anyone know how to do that?

谢谢大家!

推荐答案

您可以使用 zip

You could express the element-wise product (and matrix product) using list comprehensions, zip, and the * argument-unpacking operator:

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

elementwise_product = [[ai*bi for ai, bi in zip(*rows)] 
                       for rows in zip(matrix_a, matrix_b)]    
print(elementwise_product)
# [[1, 4, 9], [16, 25, 36], [49, 64, 81]]

matrix_product = [[sum([ai*bi for ai, bi in zip(row_a, col_b)])
                   for col_b in zip(*matrix_b)]
                  for row_a in matrix_a]
print(matrix_product)
# [[30, 36, 42], [66, 81, 96], [102, 126, 150]]

这篇关于Python矩阵乘法变体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆