0

在这段代码中,我想找到矩阵的添加。A+B

[[x + y for x,y in zip(w,v)] for w,v in zip(A,B)]

当我运行程序并在 python shell 中编写时,A+B答案是 [[7, 4], [5, 0], [4, 4], [2, 2], [-3, 3], [- 2, 4]]

答案实际上应该是[[9,6],[2,3],[2,8]]

我需要在程序中集成什么,以便调用的 Python 函数def addition (A,B)将两个矩阵作为输入并返回两个输入的相加作为结果。

4

2 回答 2

3

或者,如果您不害怕嵌套列表推导式,您可以使用单行代码来做到这一点

C = [[x + y for x,y in zip(w,v)] for w,v in zip(A,B)]
于 2013-03-27T21:52:02.520 回答
0

如果要重载+矩阵的运算符,则必须将二维列表包装到 class 和defmethod__add__中。例如(我使用你的加法功能):

>>> class Matrix(object):
    @staticmethod
    def addition (A, B):
        d=[]
        n=0
        while n < len(B):
            c = []
            k = 0
            while k < len (A[0]):
                c.append(A[n][k]+B[n][k])
                k=k+1
            n+=1
            d.append(c)
        return d
    def __init__(self,lst):
        self.lst=lst
    def __add__(self, other):
        return Matrix(Matrix.addition(self.lst, other.lst))
    def __repr__(self):
        return str(self.lst)


>>> A=Matrix([[7,4], [5,0], [4,4]])
>>> B=Matrix([[2,2], [-3,3], [-2, 4]])
>>> A+B
[[9, 6], [2, 3], [2, 8]]
于 2013-03-27T22:11:58.293 回答