Sunday, 15 September 2013

python - Making a copy of a list -


I'm trying to create a "target", a copy of "grid" I do not know why this code does not work.

  grid = [[Rand (0, 1), randint (0, 1), randint (0, 1)], [rand (0, 1), randint (0, 1) , Randint (0, 1)], [Randint (0, 1), Randint (0, 1), Randint (0, 1)]] target = [[0, 0, 0]] * (3): For range y (3): target [x] [y] = grid [x] [y] print target print grid  

Here is a result:

  [[0, 1, 0], [0, 1, 0], [0, 1, 0]] [[1, 0, 0], [0, 1, 1], [0, 1, 0]]  

this part:

  target = [[0, 0, 0]] * 3  

Create a list with the same list It is repeated so that the change in one object really reflects in all (they are the same thing) you have to make a list three times:

  target = [range] [0, 0, 0]]  

You should only use Star Operator in the list (or list multiplication) with the objects (if at all), since you do not have your position can change.

Do not Forget Use You ( x [:] use x with a list of shallow is used to make copies, such as list (x) ):

  grid = [x [target] for x]  

Or even more commonly:

  copy impaired grid = dark caps (target)  

No comments:

Post a Comment