10
$\begingroup$

I'm trying to sort a list of lists. The sublists are defined in length, but the length of the list containing it varies.

A simplified set might be:

{{1, 2, 3}, {7, 1, 4}, {3, 5, 6}, {10, 7, 1}}

but it could be:

a={{1, 2, 3}, {7, 1, 4}, {3, 5, 6}, {10, 7, 1}, {12, 4, 8}}

Sorting on the last element is built-in using

SortBy[a,Last];

How do I sort on an arbitrary element? In the example, the second.

$\endgroup$

3 Answers 3

12
$\begingroup$

To sort by a specific element use a pure function with the number in question. For your case (the second element) just do:

SortBy[a, #[[2]] &]
 {{7, 1, 4}, {1, 2, 3}, {12, 4, 8}, {3, 5, 6}, {10, 7, 1}}

You can also use Sort like this:

Sort[a, #1[[2]] < #2[[2]] &]
$\endgroup$
2
  • $\begingroup$ worked beautifully, thanks! $\endgroup$
    – Rick R
    Commented Oct 8, 2014 at 5:54
  • $\begingroup$ @RickR You're welcome. Glad I could help. $\endgroup$
    – RunnyKine
    Commented Oct 8, 2014 at 5:55
8
$\begingroup$

There is also ... Ordering

ClearAll[sortBy];
sortBy[list_, column_, ord_: Less] := list[[Ordering[list[[All, column]], All, ord]]]

Examples:

a = {{1, 2, 3}, {7, 1, 4}, {3, 5, 6}, {10, 7, 1}, {12, 4, 8}};  
sortBy[a, 2]
(* {{7,1,4},{1,2,3},{12,4,8},{3,5,6},{10,7,1}} *)

sortBy[a, 2, Greater]
(* {{10,7,1},{3,5,6},{12,4,8},{1,2,3},{7,1,4}} *)

Row[MatrixForm /@ (MapAt[Style[#, Red, Bold, 18] &, 
                         sortBy[a, #], {{All, #}}] & /@ {1, 2, 3})]

enter image description here

Row[MatrixForm /@ (MapAt[Style[#, Red, Bold, 18] &, 
                         sortBy[a, #, Greater], {{All, #}}] & /@ {1, 2, 3})]

enter image description here

$\endgroup$
2
  • $\begingroup$ oh, that's pretty cool. thanks for sharing/enlightening! $\endgroup$
    – Rick R
    Commented Oct 8, 2014 at 6:53
  • $\begingroup$ @RickR, my pleasure. Welcome to mma.se. $\endgroup$
    – kglr
    Commented Oct 8, 2014 at 6:55
2
$\begingroup$

Operator form of SortBy

a = {{1, 2, 3}, {7, 1, 4}, {3, 5, 6}, {10, 7, 1}, {12, 4, 8}};

a // SortBy[Last]

{{10, 7, 1}, {1, 2, 3}, {7, 1, 4}, {3, 5, 6}, {12, 4, 8}}

 SortBy[#[[2]] &] @ a

{7, 1, 4}, {1, 2, 3}, {12, 4, 8}, {3, 5, 6}, {10, 7, 1}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.