我怎样才能把两个矩阵作为输入
问题描述:
在这段代码中我想找到矩阵的加法。 A+B
我怎样才能把两个矩阵作为输入
[[x + y for x,y in zip(w,v)] for w,v in zip(A,B)]
当我运行该程序并在Python壳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)
需要两个矩阵作为输入和作为结果返回并添加两个输入。
答
做到这一点,你必须包装的2维列入一个类和def
方法__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]]
......它已经这样做了。为了清楚起见,只需将顶部的A和B的定义移到函数定义之下,并调用'addition(A,B)'。 – Dougal 2013-03-27 21:56:04
当您在解释器中编写“A + B”时,您只需将列表连接起来。做@Dougal所说的并称之为你的功能。如果你想重写内置的'+',你正在寻找操作符重载,哪个dspyz提到(我猜你不是,那将是奇怪的作业)。 – keyser 2013-03-27 21:58:06
如何调用我的功能? – Jett 2013-03-27 21:59:31