python运算符@重载
1063 2023-03-19 16:45
class Matrix:
def __init__(self, matrix):
self.values = matrix
def __matmul__(self, other):
a = self.values
b = other.values
return [
[
sum([float(i) * float(j) for i, j in zip(row, col)])
for col in zip(*b)
]
for row in a
]
A = [[1,2,3],[4,5,6]]
B = [[1,1], [1,1], [1,1]]
print(Matrix(A) @ Matrix(B))
#Output:
# [[6.0, 6.0], [15.0, 15.0]]
#Example 3
class Mat(list):
def __matmul__(self, B):
A = self
return Mat([[sum(A[i][k]*B[k][j] for k in range(len(B)))
for j in range(len(B[0])) ] for i in range(len(A))])
A = Mat([[1,3],[7,5]])
B = Mat([[6,8],[4,2]])
print(A @ B)
#Output:
# [[18, 14], [62, 66]]
全部评论