A=[[150,0.08,3679],[8765,30.47,21]]#自定义矩阵A
B=[[132,1.05],[87,93],[1060,42]]#自定义矩阵B
C1=[]#用于计算AB
C2=[]#用于计算BA
def AB():#自定义AB
for i in range(len(A)):#len(A)代表A的行数
C1.append([])#增加一行到C1
for j in range(len(B[0])):#len(B[0])代表B的列数
c1=sum(A[i][k]*B[k][j] for k in range(len(B)))#A的行与B的列对应元素相乘再相加
C1[i].append(c1)#增加c1到C1中的某行
print("AB结果为:",C1)
def BA():#同理BA
for i in range(len(B)):
C2.append([])
for j in range(len(A[0])):
c2=sum(B[i][k]*A[k][j] for k in range(len(A)))
C2[i].append(c2)
print("BA结果为:",C2)
'''
判断矩阵形状是否匹配
①AB匹配,BA不匹配
②BA匹配,AB不匹配
③AB,BA均匹配
④AB,BA均不匹配
'''
if len(A[0])==len(B) and len(B[0])!=len(A):AB()
elif len(B[0])==len(A) and len(A[0])!=len(B):BA()
elif len(A[0])==len(B) and len(A[0])==len(B):
AB()
BA()
else:print("矩阵形状不匹配")