简体   繁体   中英

python 2D matrix simple logic works but matrix print logic doesnt show correct matrix

Must be something really stupid that I am doing but I can't seem to figure out what is going wrong here. I am an intermediate python user.

I wrote a logic to rotate a given 2D matrix by 90 degrees. Pretty simple logic. The interesting part is that the matrix actually gets rotated but when I try to print it, it prints only the last row consistently.

Here is the logic:

def mat_rot(X):
    m = len(X)
    n = len(X[0])
    Xr = [[0]*m]*n
    for k in range(n):  # label: core_logic_for_loop
        for l in range(m):
            Xr[k][l] = X[m-1-l][k]

    m = len(Xr)
    n = len(Xr[0])
    for i in range(m):  # label: print_for_loop
        for j in range(n):
            sys.stdout.write(" i=%s j=%s, Xr=%s " %(i, j,Xr[i][j]))
        print " "
    return

So, if I give a matrix like: [[a,b,c],[d,e,f]], I should get output as [[d,a],[e,b],[f,c]]

Now here is the interesting problem I am facing. I do see that the core_logic_for_loop does contain the exact values that I want. I verified it by printing the elements in the for loop.

but by the time I get to print_for_loop and I print the values I always get the last row so instead of output being:

d a
e b
f c

I get:

f c
f c
f c

Don't seem to understand what is going wrong here : (

You can use zip here:

>>> lis = [['a','b','c'],['d','e','f']]
>>> [ x[::-1] for x in zip(*lis) ]
[('d', 'a'), ('e', 'b'), ('f', 'c')]

#or
>>> [ list(reversed(x)) for x in zip(*lis)]
[['d', 'a'], ['e', 'b'], ['f', 'c']]

When you do

Xr = [[0]*m]*n

You are actually getting several references to the same list.

m = 2
n = 2
Xr = [[0]*m]*n
print Xr
# [[0, 0], [0, 0]]
Xr[0][0] = 1
print Xr
# [[1, 0], [1, 0]]

When you change one, all change.

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