I have a list of lists of three strings in Python, e.g.,
m = [['pig', 'quartz', '1'], ['pork', 'nails', '1'], ...]
and I want to sort it by index 0, then by index 2 in reverse order, then by index 1. At each step in the sort I’d like to maintain the order imposed by the other columns. For instance,
pork barn 4
pork barn2 4
pork nails 1
pig quartz 1
quinoa pail 1
quinoa quatern 1
quail quatern 1
radish barn 1
radish barn2 1
radish inbox 3
radish snow 1
would become:
pig quartz 1
pork barn 4
pork barn2 4
pork nails 1
quail quatern 1
quinoa pail 1
quinoa quatern 1
radish inbox 3 <-
radish barn 1
radish barn2 1
radish snow 1
that is, sort by the first column, then within each group of 1st columns (pig, pork, quail, …), sort by the third column reversed, then within each group of 1st-column-3rd-column ((pig, 1), (pork, 4), (pork, 1), …), sort by the second column.
How can I do this nicely? Conceptually, if operator.itemgetter() could encode sort order along with index, I would want something like m.sort(key=operator.itemgetter(0, -2, 1)).
Use a custom comparison function:
The compare function is not optimal and might be rewritten as:
As others have pointed out this will work too: