1
$\begingroup$

Say we have a list:

{{1/2, -(Sqrt[3]/2)}, {1, 0}, {1/2, Sqrt[3]/2}, {-(1/2), Sqrt[3]/2}, {-1, 0}, {-(1/2), -(Sqrt[3]/2)}}

now we want to sort that list by looking at the second component of each sub list (call it y coordinate for ease), i.e. sort it s.t. y is in the descending order. So we'd get

{{1/2, Sqrt[3]/2},{-1/2, Sqrt[3]/2},{1,0},{-1,0},{1/2,-(Sqrt[3]/2)},{-1/2,-(Sqrt[3]/2)}}

And yeah, I should mention that if there are more than one sub lists with equal y, we would additionally (sub)sort them by descending x (first component in each of the sub lists).

I tried to use SortBy, in different forms, but I don't seem to be able to figure it out by myself. I'd appreciate any help.

$\endgroup$
  • 2
    $\begingroup$ "I tried to use SortBy" What did you try, specifically? $\endgroup$ – Szabolcs Feb 13 at 13:57
  • 2
    $\begingroup$ Likely a duplicate of mathematica.stackexchange.com/q/2729/12 $\endgroup$ – Szabolcs Feb 13 at 13:59
  • 3
    $\begingroup$ Try SortBy[list, N[-Last[#]]&] instead. $\endgroup$ – Sjoerd Smit Feb 13 at 14:25
  • 1
    $\begingroup$ You did not say what you tried originally. N[Last] is not a function, so it's not appropriate here. Use N@*Last or N[Last[#]]&. $\endgroup$ – Szabolcs Feb 13 at 14:26
  • 1
    $\begingroup$ @amator, if you've figured it out from the comments, you can answer your own question. Helps the silent majority of lurkers develop their knowledge too. $\endgroup$ – MikeY Feb 13 at 14:51
1
$\begingroup$

As suggested in the comments, the following works as desired:

Reverse[SortBy[list, N[Last[#]]&]].

$\endgroup$
  • 1
    $\begingroup$ If you use SortBy, you might as well put a minus sign in front of the sorting function so you don't have to reverse the list after sorting it. $\endgroup$ – Sjoerd Smit Feb 13 at 16:13
  • $\begingroup$ Nice, wasn't aware of that, thank you @SjoerdSmit ! $\endgroup$ – amator2357 Feb 13 at 16:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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