简体   繁体   English

如何将两个矩阵作为输入

[英]How can I take two matrices as input

In this code I'm suppose to find the addition of the matrices. 在此代码中,我想找到矩阵的加法。 A+B

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

When I run the program and write in the python shell A+B The answer comes out as [[7, 4], [5, 0], [4, 4], [2, 2], [-3, 3], [-2, 4]] 当我运行程序并在python shell A+B编写时,答案为[[7,4],[5,0],[4,4],[2,2],[-3,3] ,[-2,4]]

The answer should actually be [[9,6],[2,3],[2,8]] 答案实际上应该是[[9,6],[2,3],[2,8]]

What do I need to integrate in the program so the Python function called def addition (A,B) takes the two matrices as input and return with the addition of the two input as the result. 我需要在程序中集成什么,因此称为def addition (A,B)的Python函数将两个矩阵作为输入,然后将两个输入相加作为结果返回。

或者,如果您不害怕嵌套列表推导,则可以单线执行

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

If you want to overload the operator + for your matrices you have to wrap the 2 dimensional list into a class and def the method __add__ . 如果你想重载运营商+你的矩阵,你必须包装在2维列表到一个类和def方法__add__ For example (I use your addition function): 例如(我使用您的加法函数):

>>> 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]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM