Mongzyy
Mongzyy

Reputation: 123

Replace index in list

I have a list containing n identical 3x3 matrices, where n is the number of zeros in one such matrix.

In my first matrix, I want to replace the first 0 with the integer 2. In the second matrix, I want to replace the second 0 with 2. This goes on until the n:th matrix where I want to replace the n:th 0 with 2. I.e. every matrix should have only one index replaced.

My code so far:

def replaceZero(x):

    # Omitted code where I count number of 0 in x
    n = 9 # in this example

    # Creating a list which holds n matrices
    lists = []
    for i in range(0,n):
        lists.append(x)

    # Replacing the i:th 0 with 2
    for i in range(0,n):
        m = -1
        for j in range(0,3):
            for k in range(0,3):
                if lists[i][j][k] == 0:
                    m = m + 1
                    if m == i:
                        lists[i][j][k] = 2

    return lists

# Example of a matrix
x = [[0,0,0],[0,0,0],[0,0,0]]

I can't figure out why it doesn't work. Although, too many zeros are replaced and the replacement is identical for each matrix.

I am trying to increment m with 1 each time a zero is found. Only when m has the same value as the index of the current matrix should the replacement occur.

Upvotes: 0

Views: 140

Answers (2)

Prune
Prune

Reputation: 77847

The immediate problem is that you build your list using nine references to x. You don't have nine copies of x; you have nine references to the same x. If you change one, you change them all.

Instead, alter with this technique:

import copy
...
    lists.append(copy.deepcopy(x))

The full documentation is here. Since you have a multi-level structure, you need to use deepcopy; if you use just copy, you'll get nine matrices that point to the same three vectors of zeros.

Does this get you moving?


Glad to be of help. You can also simplify the inner loops:

for i in range(0,n):
    j = i / 3
    k = i % 3
    lists[i][j][k] = 2

Upvotes: 1

Irshad Bhat
Irshad Bhat

Reputation: 8709

All you need to do is to append the matrix using copy by value not by reference. This can be done using copy.deepcopy as:

import copy 

and replace:

lists.append(x)

with

lists.append(copy.deepcopy(x))

Upvotes: 1

Related Questions