I have a multi-column table of data, each row unique, and I want to know how to sort it based on multiple columns. If sorting alphabetically a solution is already described here. However, instead of alphabetical sorting, I need to sort each column based on a custom ordering stored in another list. For example, if my table is
mytable = [
('A1', 'B1', 'C1'),
('A1', 'B2', 'C2'),
('A2', 'B2', 'C1'),
('A2', 'B2', 'C2')
]
I might want the first column to be ordered [‘A2′,’A1’], the second column to be ordered [‘B1′,’B2’], and the third column to be ordered [‘C2′,’C1’]. The proper result would be
mytable = [
('A2', 'B2', 'C2'),
('A2', 'B2', 'C1'),
('A1', 'B1', 'C1'),
('A1', 'B2', 'C2')
]
This will do what you’re looking for:
In practice, the columns might not all be sorted, or might be sorted in a priority other than left-right order. That could be solved by attaching an index to each and adapting the algorithm accordingly.