3
$\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$
8
  • 2
    $\begingroup$ "I tried to use SortBy" What did you try, specifically? $\endgroup$
    – Szabolcs
    Commented Feb 13, 2019 at 13:57
  • 2
    $\begingroup$ Likely a duplicate of mathematica.stackexchange.com/q/2729/12 $\endgroup$
    – Szabolcs
    Commented Feb 13, 2019 at 13:59
  • 3
    $\begingroup$ Try SortBy[list, N[-Last[#]]&] instead. $\endgroup$ Commented Feb 13, 2019 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
    Commented Feb 13, 2019 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
    Commented Feb 13, 2019 at 14:51

3 Answers 3

1
$\begingroup$

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

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

$\endgroup$
2
  • 2
    $\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$ Commented Feb 13, 2019 at 16:13
  • $\begingroup$ Nice, wasn't aware of that, thank you @SjoerdSmit ! $\endgroup$
    – amator2357
    Commented Feb 13, 2019 at 16:14
1
$\begingroup$
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)}};

Using ReverseSortBy (new in 12.0)

ReverseSortBy[N @* Last] @ list

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

$\endgroup$
1
$\begingroup$
l = 
  {{1/2, -(Sqrt[3]/2)}, {1, 0}, {1/2, Sqrt[3]/2}, 
  {-(1/2), Sqrt[3]/2}, {-1, 0}, {-(1/2), -(Sqrt[3]/2)}};

The ordering using OrderingBy:

o = Flatten[RotateRight[Sort /@ Partition[Reverse@OrderingBy[#, Abs], 2]]] &@l;

Apply the ordering:

l[[o]]

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

$\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.