如何实现对所有子矩阵元素的加法? [英] How to implement addition to all submatrix elements?
问题描述
我正在尝试通过简单的python(没有numpy等)实现矩阵类,以实现简单的操作.
I'm trying to implement matrix class for simple operations with plain python (no numpy and etc.).
这是其中的一部分:
class Matrix(list):
def __getitem__(self, item):
try:
return list.__getitem__(self, item)
except TypeError:
rows, cols = item
return [row[cols] for row in self[rows]]
它允许执行以下操作:
m = Matrix([[i+j for j in [0,1,2,3]] for i in [0,4,8,12]])
print(m[0:2, 0:2])
will print: [[0, 1], [4, 5]]
我还希望能够将所有子矩阵元素添加/乘以给定值,例如:
I also want to be able to add/multiply all submatrix elements by given value, like:
m[0:2, 0:2] += 1
print(m[0:2, 0:2])
should print: [[1, 2], [5, 6]]
目前尚不清楚我应该采用哪种魔术方法使其起作用?
It's not clear which magic methods should I implement to make it work?
推荐答案
首先,从list
继承是一个不好的举动.矩阵不支持列表所执行的操作;例如,您不能append
到或extend
矩阵,并且项目分配完全不同.您的矩阵应包含一个列表,而不是列表.
First, inheriting from list
is a bad move here. A matrix doesn't support the kinds of operations a list does; for example, you can't append
to or extend
a matrix, and item assignment is completely different. Your matrix should contain a list, not be a list.
关于所需的魔术方法,m[0:2, 0:2] += 1
大致翻译为以下内容:
As for what magic methods you need, m[0:2, 0:2] += 1
roughly translates to the following:
temp = m.__getitem__((slice(0, 2), slice(0, 2)))
temp = operator.iadd(temp, 1)
m.__setitem__((slice(0, 2), slice(0, 2)), temp)
其中operator.iadd
尝试使用temp.__iadd__
,temp.__add__
和(1).__radd__
进行加法.
where operator.iadd
tries temp.__iadd__
, temp.__add__
, and (1).__radd__
to perform the addition.
您需要实现__getitem__
和__setitem__
来检索子矩阵并分配新的子矩阵.另外,__getitem__
将需要返回矩阵,而不是列表.
You need to implement __getitem__
and __setitem__
to retrieve the submatrix and assign the new submatrix. Additionally, __getitem__
will need to return a matrix, rather than a list.
您可能应该同时实现__add__
和__iadd__
;在这种情况下,仅__add__
就足够了,但__iadd__
对于像m += 1
这样的操作就地工作而不是用新的矩阵对象替换m
来说是必要的.
You should probably implement both __add__
and __iadd__
; while __add__
alone would be sufficient for this case, __iadd__
will be necessary for operations like m += 1
to work in-place instead of replacing m
with a new matrix object.
这篇关于如何实现对所有子矩阵元素的加法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!