Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3: sort rows in 2D matrix, where columns are lists

I have created a 2D matrix like this:

45  67  Row  Fine
25  22  Abe  Real
58  54  Abe  Noon

Each column is a list. The values in the rows are connected together, so the values in the third row with the indexnumber 2 belong to each other.

I want to sort the rows, first on the third row, and then on the fourth row, so that it becomes:

58  54  Abe  Noon  
25  22  Abe  Real 
45  67  Row  Fine

I don't know what way to go. I could sort one list, the one with the values of the third column. Then find out the new indexnumbers and compare them with the old. Then I could adjust the other lists as well, so that all rows are correct again. But then I still need to sort the fourth row.

I see some code for sorting a list of lists here , but I then need lists of rows instead of columns (if I understand it well).

Or is creating a dictionary a smart way to go?

like image 274
JOVERN Avatar asked Jul 22 '26 17:07

JOVERN


1 Answers

You have a list of columns. To make it into a list of rows, you can just use zip:

iterable_of_rows = zip(*my_list_of_columns)

Combining that with the typical way to do these sorts:

import operator
sorted_list_of_rows = sorted(zip(*my_list_of_columns), key = operator.itemgetter(2,3))
list_of_columns = list(zip(*sorted_list_of_rows))

And testing:

>>> my_list_of_columns = [[45,25,48],[67,22,54],["Row","Abe","Abe"],["Fine","Real","Noon"]]
>>> import operator
>>> sorted_list_of_rows = sorted(zip(*my_list_of_columns), key = operator.itemgetter(2,3))
>>> list_of_columns = list(zip(*sorted_list_of_rows))
>>> list_of_columns
[(48, 25, 45), (54, 22, 67), ('Abe', 'Abe', 'Row'), ('Noon', 'Real', 'Fine')]
like image 132
mgilson Avatar answered Jul 24 '26 08:07

mgilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!