Home > Net >  Flip rows in a Matrix(2D) list in Python
Flip rows in a Matrix(2D) list in Python

Time:07-07

I have a 2D list called tab:

[[1, 2, 3],   # <---  first row
[4, 5, 6],    # <---  2nd row
[7, 8, 9]]    # <---- last row

with tab[lines][columns]. For instance, tab[0][1] = 2. I want to reverse the order of each column to get the output format:

7 8 9   # <---- become first row
4 5 6   # <===== 2nd row. no change
1 2 3   # <----- become last row

CodePudding user response:

You need to use [::-1] operator as if it were a string:

l = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]

l = l[::-1]
print(l)

Output:

[[7, 8, 9], [4, 5, 6], [1, 2, 3]]

CodePudding user response:

You can also call reverse() to reverse the order in a list. In your case, this would mean doing the following:

>>> tab.reverse()
>>> tab
[[7, 8, 9], [4, 5, 6], [1, 2, 3]]

If you wanted to reverse the order on the minor index of your 2D array, you could combine this with map, like so:

>>> list(map(lambda c: c.reverse(), tab))
>>> tab
[[3, 2, 1], [6, 5, 4], [9, 8, 7]]

CodePudding user response:

Since no one mention numpy, I just add this for completeness/reference:

import numpy as np
>>> A = np.array([(1,2,3),(4,5,6),(7,8,9)])
>>> A
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
>>> flipped2 = np.flip(A, axis=0)
>>> flipped2
array([[7, 8, 9],
       [4, 5, 6],
       [1, 2, 3]])
  • Related