我正在尝试使用嵌套 while 循环对给定的硬编码矩阵进行矩阵乘法...
正确答案应该是 [[6,12], [15,30], [24,48]]
但是我的代码的输出是 [[6,12], [6,12], [6,12]]
我该怎么办?
a=[[1,2,3],[4,5,6],[7,8,9]]
b=[[1,2],[1,2],[1,2]]
c=[]
cola=len(a)
rowa=len(a[0])
colb=len(b)
rowb=len(b[0])
r,s,t,u,sum = 0,0,0,0,0
c=[([0]*rowb)]*cola
print c
while s<cola:
while u<rowb:
while t<colb:
d=a[s][t]*b[t][r]
sum+=d
t+=1
c[s][r]=sum
sum=0
u+=1
t=0
r+=1
r=0
s+=1
print c
最佳答案
当你这样做时 -
c=[([0]*rowb)]*cola
您只是复制内部列表cola
次,这是浅复制,因此每个内部列表都是对同一对象的引用,因此当您更改其中一个内部列表中的元素时,它影响所有内部列表。相反,尝试使用列表理解来创建 c
列表。
示例 -
c = [[0 for _ in range(rowb)] for _ in range(cola)]
此外,逻辑中的另一个小问题是,您使用 r
来表示 b
中的元素,但在 while 循环中您要检查 - u
,您应该检查 r
。示例-
while s<cola:
while r<rowb:
关于python - Python 语言中的矩阵乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31432979/