简体   繁体   中英

Adding elements to a matrix in python

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

i used this code to enter a matrix, it didn't show any error but after inserting all the elements, when the matrix is printed, the 2 rows were the same...i cant see any error in the code :-(

output

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]]

This is a tricky one, that got me for a second.

This line here duplicates the reference to an anonymous object that comprises of mat*n :

mat=[(mat*n)]*m

So when you iterate through the rows, it updates each entry in every row, because they are all the same object .

As proof, using the id() function we can see that both rows in mat share the same memory!

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

Instead, consider a list comprehension to build your empty matrix:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM