python的矩阵加法和乘法
2013-11-23 01:08
274 查看
本来以为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
然后搜索了一下资料,果断有个很棒的,不过不知道有没有更棒的。
代码片段来源于:http://www.hustyx.com/python/
这里贴出我写的特别不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]
代码片段来源于:http://www.hustyx.com/python/
相关文章推荐
- python 核心编程 第六章 习题16 矩阵加法和乘法
- Python实现矩阵加法和乘法的方法分析
- Python2.7学习笔记-矩阵乘法matrix vs. ndarray ; dot vs. inner,
- CUDA编程入门:向量加法和矩阵乘法
- Python 小议2:用循环和递归函数分别求100以内的数字的加法和乘法。
- Python算法 Hadoop实例-单轮MapReduce的矩阵乘法
- python实现矩阵乘法
- C#实现矩阵加法、取负、数乘、乘法的方法
- java第五周(矩阵中数据的位置变换功能、矩阵的加法功能、矩阵的乘法功能)
- Python 矩阵与矩阵以及矩阵与向量的乘法
- 多线程--Python下载(支持断点续传) & Java多线程计算矩阵乘法
- java第二周作业--实现矩阵的加法和乘法运算
- 【[Offer收割]编程练习赛13 D】骑士游历(矩阵模板,乘法,加法,乘方)
- python中实现矩阵乘法
- 算法导论程序4--矩阵乘法的分治算法(Python)
- 矩阵基础 (3). 分块矩阵的加法和乘法运算
- python tensorflow学习笔记(四)矩阵乘法
- python tensorflow学习笔记(五)矩阵乘法运算
- Python中的几种矩阵乘法
- Java上机 第五周 任务6 矩阵中数据的位置变换功能、矩阵的加法功能、矩阵的乘法功能