矩阵库
您可以使用numpy
支持此功能的模块。
>>> import numpy as np
>>> a = np.matrix([[1, 2], [3, 4]])
>>> b = np.matrix([[2, 2], [2, 2]])
>>> a+b
matrix([[3, 4],
[5, 6]])
本土解决方案:重量级
假设您想自己实现它,您将设置以下机制,它可以让您定义任意成对操作:
from pprint import pformat as pf
class 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 和关键字参数,您可以在 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]]