Is there an easy way to sort a list on multiple levels of criteria?
By this I mean, first the list should be sorted according by criteria A (the same as using the usual sort function, Sort[list, A[#1] < A[#2] & ]
. I am a big fan of using the pure ordering function in Sort.). However, then I want to have elements with the same value for criterion A to be sorted within their class by criterion B. In general, I would like to do this to an arbitrary depth of criteria.
An example would be, given a set of colored blocks, first sort the blocks alphabetically by shape, then (maintaining that all the squares come before all the triangles) sort each cluster of shapes alphabetically by their colors. (Blue square, Purple square, Red square, black triangle, orange triangle, yellow triangle, etc.)
Answer
This is implemented in SortBy
:
Because this function does not perform a pairwise compare, you would need to be able to recast your sort function to produce a canonical ordering. On the upside, if you are able to do so it will be far more efficient than Sort
.
f1 = Mod[#, 4] &;
f2 = Mod[#, 7] &;
SortBy[Range@10, {f1, f2}]
{#, f1@#, f2@#} & /@ % // Grid
{8, 4, 1, 9, 5, 2, 10, 6, 7, 3}
$\begin{array}{r} 8 & 0 & 1 \\ 4 & 0 & 4 \\ 1 & 1 & 1 \\ 9 & 1 & 2 \\ 5 & 1 & 5 \\ 2 & 2 & 2 \\ 10 & 2 & 3 \\ 6 & 2 & 6 \\ 7 & 3 & 0 \\ 3 & 3 & 3 \end{array}$
Also see:
Comments
Post a Comment