脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python实现矩阵加法和乘法的方法分析

Python实现矩阵加法和乘法的方法分析

2020-12-26 00:32逍遥浪人 Python

这篇文章主要介绍了Python实现矩阵加法和乘法的方法,结合实例形式对比分析了Python针对矩阵的加法与乘法运算相关操作技巧,需要的朋友可以参考下

本文实例讲述了Python实现矩阵加法乘法的方法。分享给大家供大家参考,具体如下:

本来以为python的矩阵用list表示出来应该很简单可以搞。。其实发现有大学问。

这里贴出我写的特别不pythonic的矩阵加法,作为反例。

?
1
2
3
4
5
6
7
8
9
10
def add(a, b):
   rows = len(a[0])
   cols = len(a)
   c = []
   for i in range(rows):
     temp = []
     for j in range(cols):
       temp.append(a[i][j] + b[i][j])
     c.append(temp)
   return c

然后搜索了一下资料,果断有个很棒的,不过不知道有没有更棒的。

矩阵加法

?
1
2
3
def madd(M1, M2):
  if isinstance(M1, (tuple, list)) and isinstance(M2, (tuple, list)):
    return [[m+n for m,n in zip(i,j)] for i, j in zip(M1,M2)]

矩阵乘法

?
1
2
3
4
5
6
def multi(M1, M2):
  if isinstance(M1, (float, int)) and isinstance(M2, (tuple, list)):
    return [[M1*i for i in j] for j in M2]
  if isinstance(M1, (tuple, list)) and isinstance(M2, (tuple, list)):
    return [[sum(map(lambda x: x[0]*x[1], zip(i,j)))
         for j in zip(*M2)] for i in M1]

希望本文所述对大家Python程序设计有所帮助。

原文链接:http://blog.csdn.net/fkysly/article/details/16893897

延伸 · 阅读

精彩推荐