在python中向矩阵添加元素

时间:2015-11-11 04:58:00

标签: python matrix

m=int(input("enter the number of rows"))
n=int(input("enter the number of columns"))
mat=[0]
mat=[(mat*n)]*m
for i in range(m):
 for j in range(n):
  print "enter element of ",(i+1)," th row ",(j+1)," th column "
  mat[i][j]=int(input("?"))
  print mat
print mat

我使用此代码输入矩阵,它没有显示任何错误但插入所有元素后,打印矩阵时,2行是相同的...我无法看到代码中的任何错误: - (

输出

enter the number of rows2
enter the number of columns3
enter element of  1  th row  1  th column 
?1
[[1, 0, 0], [1, 0, 0]]
enter element of  1  th row  2  th column 
?2 
[[1, 2, 0], [1, 2, 0]]
enter element of  1  th row  3  th column 
?3
[[1, 2, 3], [1, 2, 3]]
enter element of  2  th row  1  th column 
?4
[[4, 2, 3], [4, 2, 3]]
enter element of  2  th row  2  th column 
?5
[[4, 5, 3], [4, 5, 3]]
enter element of  2  th row  3  th column 
?6
[[4, 5, 6], [4, 5, 6]]
[[4, 5, 6], [4, 5, 6]]

1 个答案:

答案 0 :(得分:2)

这是一个棘手的问题,让我有一秒钟。

此行重复对包含mat*n

的匿名对象的引用
mat=[(mat*n)]*m

因此,当您遍历行时,它会更新每一行中的每个条目,因为它们所有相同的对象

作为证明,使用id()函数,我们可以看到mat中的两行共享相同的内存!

>>> id(mat[0])
139943023116440
>>> id(mat[1])
139943023116440

相反,请考虑使用列表推导来构建空矩阵:

>>> mat = [[0]*n for i in range(m)]
>>> mat[1][2] = 5
>>> mat
[[0, 0, 0], [0, 0, 5]]