简体   繁体   中英

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?

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')]

Working with a list of columns directly is troublesome, but you can use zip and work with rows:

>>> print(data)
[[45, 25, 58], [67, 22, 54], ['Row', 'Abe', 'Abe'], ['Fine', 'Real', 'Noon']]

>>> print(sorted(zip(*data), key=lambda x: (x[2], x[3])))
[(58, 54, 'Abe', 'Noon'), (25, 22, 'Abe', 'Real'), (45, 67, 'Row', 'Fine')]

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