Domanda

I have a matrix-style array, that (hypothetically) looks like this:

mat = [[0,2,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
imat = mat
for i in xrange(4):
    for j in xrange(4):
        imat[j][i] = mat[i][j]
for i in xrange(4):
    for j in xrange(4):
        imat[j][i] = mat[i][j]

The code basically switches the row/column from "mat" to "imat".

The results: mat: [[0, 2, 0, 0], [2, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] imat: [[0, 2, 0, 0], [2, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

Could anyone tell me why the array items are duplicating like this?
Also, if there is a more efficient way to do this operation, that would also be appreciated.

È stato utile?

Soluzione

The problem is in this line:

imat = mat

Instead you should do this, to allocate a new 4x4 matrix at the beginning:

imat = [[0]*4 for _ in xrange(4)]

What's happening is that you didn't initialize imat correctly, you only assigned a reference to mat so both objects are one and the same, so no modification is being performed. Also, a much simpler alternative for transposing a matrix would be:

imat = [list(m) for m in zip(*mat)]

Altri suggerimenti

Also, if there is a more efficient way to do this operation, that would also be appreciated.

Yes, it's called a matrix transpose operation, which in Python is done using the builtin function zip() with the *-unpacking:

imat = zip(*mat)

As to why your current code doesn't work, @Óscar López has it right, doing imat = mat does not create a new copy of the matrix.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top