Avi
Avi

Reputation: 2283

Revesing matrix columns order in basic way in python

I would like to invert the order of each matrix column as follows:

A = [[ 4,  8, 12, 16],
     [ 3,  7, 11, 15],
     [ 2,  6, 10, 14],
     [ 1,  5,  9, 13]]

The required result:

A = [[ 1,  5,  9, 13],
     [ 2,  6, 10, 14],
     [ 3,  7, 11, 15],
     [ 4,  8, 12, 16]]

As can be seen each column changed its order.

I use the following code for it:

B = [row[:] for row in A]

k = 0
for i in range(len(A), -1, -1):
    k = k + 1,
    for j in (range(len(A))):
        B[k, j] = A[i, j]

print(B)

However, I get the following error:

TypeError                                 Traceback (most recent call last)
<ipython-input-91-72c0a8d534ec> in <module>()
      9     k = k + 1,
     10     for j in range(len(A)):
---> 11         B[k, j] = A[i, j]
     12 
     13 print(B)

TypeError: list indices must be integers or slices, not tuple

Upvotes: 1

Views: 47

Answers (1)

Mad Physicist
Mad Physicist

Reputation: 114350

A is a nested list, not a numpy array. To flip it vertically, reverse the outer list:

A = A[::-1]

To make a full copy:

B = [list(row) for row in A[::-1]]

You can replace list(row) with row[:] or row.copy().

If you just want to do proper 2D indexing, you need to pass a separate index to each object in the nested structure:

B[k][j] = A[i][j]

The index [k, j] is really [(k, j)]. Numpy arrays can accept a tuple in their index, but list objects can not, as the error tells you. Instead, you need to access each sub-list separately. B[k] is a reference to a nested list, so you can assign an element to it with B[k][j] = ....

You may also want to be careful with how you construct your outer loop. The expression range(len(A), -1, -1) starts with len(A), which is out of bounds in your list (by definition). You probably want to use range(len(A) - 1, -1, -1).

Upvotes: 1

Related Questions