Python实现矩阵加法和乘法的方法分析
2019/7/13 22:31:30
本文主要是介绍Python实现矩阵加法和乘法的方法分析,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
本文实例讲述了Python实现矩阵加法和乘法的方法。分享给大家供大家参考,具体如下:
本来以为python的矩阵用list表示出来应该很简单可以搞。。其实发现有大学问。
这里贴出我写的特别不pythonic的矩阵加法,作为反例。
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
然后搜索了一下资料,果断有个很棒的,不过不知道有没有更棒的。
矩阵加法
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)]
矩阵乘法
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相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。
这篇关于Python实现矩阵加法和乘法的方法分析的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-27使用python 将ETH账户的资产打散
- 2024-09-26Python编程基础
- 2024-09-2610 种方法写出更好的 Python 代码
- 2024-09-25Python编程基础详解
- 2024-09-25Python编程入门教程
- 2024-09-25从零开始使用Python构建LLaMA 3
- 2024-09-23Python中理解和使用树形结构的简单教程
- 2024-09-23Python 编程基础入门
- 2024-09-18初探Python股票自动化交易:入门指南
- 2024-09-18Python量化入门:轻松掌握量化分析基础与实战