Initializing matrix in Python using “[[0]*x]*y” creates linked rows?

廉价感情. 提交于 2020-02-03 10:47:09

问题


Initializing a matrix as so seems to link the rows so that when one row changes, they all change:

>>> grid = [[0]*5]*5
>>> grid
[[0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0]]
>>> grid[2][2] = 1
>>> grid
[[0, 0, 1, 0, 0],
 [0, 0, 1, 0, 0],
 [0, 0, 1, 0, 0],
 [0, 0, 1, 0, 0],
 [0, 0, 1, 0, 0]]

How can I avoid this?


回答1:


grid = [[0]*5 for i in range(5)]

Note: [int]*5 copies the int 5 times (but when you copy an int you just copy the value). [list]*5 copies the reference to the same list 5 times. (when you copy a list you copy the reference that points to the list in memory).



来源:https://stackoverflow.com/questions/9658459/initializing-matrix-in-python-using-0xy-creates-linked-rows

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!