Aleix Aleix - 4 months ago 24
Python Question

Sort table (list of lists) according to specific ordered list (and other options)

I've done some research but could not find the way to order a table (list of lists) by a column following a specific order (i.e. given by a specific list).

I have a table made by a list of lists where each sublist represent a row of the table and each of its elements are the column values of that row.

My_table has 4 columns and I need to sort the table according to several options.
I am currently sorting it by the first column and then by the second column, as follows

My_table=sorted(My_table, key=lambda a: ( a[0], a[1]))

Now I need to sort My_table by the first column first and then by the third column, but the third column (which contains only integers) must be sorted according to a specific list where the integers have a specific order, say: custom_list=[3,0,1,2]. (Note: the integers of the list are all the possible values that can appear in that column, but not all of them necessarily appear).

How do I apply that sorting?

cmd cmd

maybe something like this?

order_of_3rd = [3,0,1,2]
My_table.sort(key=lambda a: (a[0], order_of_3rd.index(a[2])))

Note: if you are just assigning the sorted list back to the original list, you may as well use the inplace list sort