I have a minimal working example (MWE) list called listToSort
that is a list of string triplets:
listToSort = {{"B", "X", "Y"}, {"C", "Y", "X"}, {"C", "X", "Y"}, {"A", "X", "Y"}};
I wish to sort listToSort
by the first element in each triplet so that the triplets starting with "C"
come first, the triplets starting with "B"
come next, and the triplets starting with "A"
come last. I would like the second and third elements to be sorted in canonical order (i.e., "X"
comes before "Y"
).
One way to do this is with SortBy
and Which
:
SortBy[listToSort, Which[#[[1]] == "C", 1, #[[1]] == "B", 2, #[[1]] == "A", 3] &]
{{"C", "X", "Y"}, {"C", "Y", "X"}, {"B", "X", "Y"}, {"A", "X", "Y"}}
However, it is quite verbose and takes a lot of typing to use Which
as above. Switch
, on the other hand, uses a more compact syntax and still gives the desired output:
SortBy[listToSort, Switch[#[[1]], "C", 1, "B", 2, "A", 3] &]
{{"C", "X", "Y"}, {"C", "Y", "X"}, {"B", "X", "Y"}, {"A", "X", "Y"}}
But, what if I want to use Switch
in tandem with a list of scoring values called atomsScoreList
?
atomsScoreList = {{"C", 1}, {"B", 2}, {"A", 3}};
I notice that I can use Apply
to obtain a Switch
function analogous to the example above. For instance:
Apply[Switch["C", ##] &, Flatten[atomsScoreList]]
Apply[Switch["B", ##] &, Flatten[atomsScoreList]]
Apply[Switch["A", ##] &, Flatten[atomsScoreList]]
1
2
3
How do I incorporate a similar Switch
function in a call to SortBy
? In particular, could you please help me understand how I can use the slots (#
and ##
) and &
to specify the correct pure function(s)?
For example, this attempt fails to yield the desired output:
SortBy[listToSort, Apply[Switch[#[[1]] &, ##] &, Flatten[atomsScoreList]]]
I probably have the &
s in the wrong places. Could you please help me?
(By the way, I'm running a very old version of Mathematica: version 9. I would like potential solutions to work in version 9.)