python中如何用for语句选矩阵运算_以最简洁的Python代码实现常用矩阵运算-爱代码爱编程
以最简洁的Python代码实现常用矩阵运算
2020-07-22 08:14
阅读数 49
本文是讲用Python实现矩阵的加法运算和乘法运算,写几层for循环,实现矩阵加法和乘法并不困难,但关键是要足够简洁,这个可让我费了不少脑子。先直接上代码吧。
#矩阵表示形式 M = [ [a1, a2, a3], [a4, a5, a6], [a7, a8, a9] ] #矩阵加法 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的人应该很快能弄懂。主要用到了zip函数,该函数的功能就是将若干个list的元素一一对应起来,map函数相当于是一层for循环,即将某list里的元素依次执行某函数,得到一个新的list。特别注意zip(*M2),就这么简单就能取到矩阵的每一列元素。对,就是这些,对着代码好好琢磨琢磨吧