矩阵库
您可以使用
numpy支持此功能的模块。
>>> import numpy as np>>> a = np.matrix([[1, 2], [3, 4]])>>> b = np.matrix([[2, 2], [2, 2]])>>> a+bmatrix([[3, 4], [5, 6]])
本土解决方案:重量级
假设您想自己实现它,那么您将设置以下机器,使您可以定义任意成对操作:
from pprint import pformat as pfclass Matrix(object): def __init__(self, arrayOfRows=None, rows=None, cols=None): if arrayOfRows: self.data = arrayOfRows else: self.data = [[0 for c in range(cols)] for r in range(rows)] self.rows = len(self.data) self.cols = len(self.data[0]) @property def shape(self): # myMatrix.shape -> (4,3) return (self.rows, self.cols) def __getitem__(self, i): # lets you do myMatrix[row][col return self.data[i] def __str__(self): # pretty string formatting return pf(self.data) @classmethod def map(cls, func, *matrices): assert len(set(m.shape for m in matrices))==1, 'Not all matrices same shape' rows,cols = matrices[0].shape new = Matrix(rows=rows, cols=cols) for r in range(rows): for c in range(cols): new[r][c] = func(*[m[r][c] for m in matrices], r=r, c=c) return new
现在,添加成对方法非常容易:
def __add__(self, other): return Matrix.map(lambda a,b,**kw:a+b, self, other) def __sub__(self, other): return Matrix.map(lambda a,b,**kw:a-b, self, other)
例:
>>> a = Matrix([[1, 2], [3, 4]])>>> b = Matrix([[2, 2], [2, 2]])>>> b = Matrix([[0, 0], [0, 0]])>>> print(a+b)[[3, 4], [5, 6]]>>> print(a-b)[[-1, 0], [1, 2]]
您甚至可以添加成对取幂,取反,二进制运算等。在此不做演示,因为最好将和*留给矩阵乘法和矩阵求幂。
本土解决方案:轻巧
如果您只想以一种非常简单的方式将操作映射到两个嵌套列表矩阵上,则可以执行以下操作:
def listmatrixMap(f, *matrices): return [ [ f(*values) for c,values in enumerate(zip(*rows)) ] for r,rows in enumerate(zip(*matrices)) ]
演示:
>>> listmatrixMap(operator.add, a, b, c))[[3, 4], [5, 6]]
通过附加的if-else和keyword参数,您可以在lambda中使用索引。下面是一个如何编写矩阵行顺序
enumerate函数的示例。为了清楚起见,上面省略了if-else和关键字。
>>> listmatrixMap(lambda val,r,c:((r,c),val), a, indices=True)[[((0, 0), 1), ((0, 1), 2)], [((1, 0), 3), ((1, 1), 4)]]
编辑
所以我们可以这样写上面的
add_matrices函数:
def add_matrices(a,b): return listmatrixMap(add, a, b)
演示:
>>> add_matrices(c, d)[[11, 4], [12, 6], [15, 19]]



