[英]__add__ matrices method in python 2.7
I'm newbee in Python, so i need your help. 我是Python的新手,所以我需要你的帮助。 Programm must add and substract random matrices.
程序必须添加和减去随机矩阵。
import random
class Matrix:
def __init__(self):
self.mat = [[]]
def gen_ran_numb(self,row=5,col=5):
self.mat=[[random.randint(0,10) for z in xrange(col)] for z in xrange(row)]
def print_matrix(self):
print self.mat
def __add__(self,b):
mat=[]
for j in range(len(self.mat)):
temp=[]
for k in range(len(self.mat[0])):
x=self.mat[j][k] + b.mat[j][k]
temp.append(x)
mat.append(temp)
rez=mat
return rez
def __sub__(self,b):
mat=[]
for j in range(len(self.mat)):
temp=[]
for k in range(len(self.mat)):
x=self.mat[j][k] - b.mat[j][k]
temp.append(x)
mat.append(temp)
return mat
a=Matrix()
b=Matrix()
c=Matrix()
a.print_matrix()
a.gen_ran_numb(5,5)
b.gen_ran_numb(5,5)
c.gen_ran_numb(5,5)
a.print_matrix()
b.print_matrix()
c.print_matrix()
print b+a
print b+a+c
If i'm adding 2 matrices it work great, but if i'm adding 3 or 4 matrices i took this error: 如果我添加2个矩阵,它工作得很好,但如果我添加3或4个矩阵,我会犯这个错误:
Traceback (most recent call last):
File "C:/Users/Вадик/Documents/Python/task.py", line 40, in <module>
print b+a+c
TypeError: can only concatenate list (not "instance") to list
I don't understand what i do wrong. 我不明白我做错了什么。 Please help me.
请帮我。 Thank you!
谢谢!
The problem is you're not returning a Matrix
object but an actual matrix, ie a list of a lists. 问题是你没有返回
Matrix
对象而是返回实际矩阵,即列表列表。 So when you concatenate 2 objects it's ok, but when you do it with 3 objects, you're actually trying to concatenate a list object with a Matrix
object. 因此,当您连接2个对象时,它是可以的,但是当您使用3个对象时,您实际上是在尝试将列表对象与
Matrix
对象连接起来。
In other words, simply change the function to return a new instance, like so: 换句话说,只需更改函数以返回新实例,如下所示:
def __add__(self, b):
res = Matrix()
res.mat = [] #to avoid an unwanted empty list at the beginning of new matrix
for j in range(len(self.mat)):
temp = []
for k in range(len(self.mat[j])):
x = self.mat[j][k] + b.mat[j][k]
temp.append(x)
res.mat.append(temp)
return res
You probably want to similarly change __sub__
as well. 您可能也希望同样更改
__sub__
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.