6
$\begingroup$

I wish to sort the below list upon the first elements:

 {{1/2 (-1 - Sqrt[2]), {{1, 11}, {1, 12}, {2, 11}}}, 
 {-1 - Sqrt[2], {{5, 11}, {5, 12}}}, 
 {1/2 (1 - Sqrt[2]), {{1, 9}, {1, 10}}},
 {1 - Sqrt[2], {{7, 9}, {7, 10}}}, 
 {1/2 (-1 + Sqrt[2]), {{1, 7}, {1, 8}}}}

The desired output can be shaped as:

{{-2.414, {{5, 11}, {5, 12}}}, 
 {-1.207, {{1, 11}, {1, 12},{2,11}}}, 
 {-0.414, {{7, 9}, {7, 10}}}, 
 {-0.207, {{1, 9}, {1,10}}}, 
 {0.207, {{1, 7}, {1, 8}}}}

where the first elements are numeric values (without Sqrt symbols) and just for 3-digit precision. I have tried with N function. But the problem gives rise the effects on any pairs for example output be shaped as {-2.41421, {{5., 11.}, {5., 12.}}} (with a dot after 5 or 11. Another problem is related to sorting of list just based on the first elements and NOT other elements.

$\endgroup$
  • $\begingroup$ If you want to keep the exact forms of the first element you can use SortBy[lst, First[N[#]]&] $\endgroup$ – N.J.Evans May 16 at 17:43
9
$\begingroup$
SortBy[MapAt[N, lst, {All, 1}], First]

{{-2.41421, {{5, 11}, {5, 12}}}, {-1.20711, {{1, 11}, {1, 12}, {2, 11}}}, {-0.414214, {{7, 9}, {7, 10}}}, {-0.207107, {{1, 9}, {1, 10}}}, {0.207107, {{1, 7}, {1, 8}}}}

SortBy[N @* First] @ lst

{{-1 - Sqrt[2], {{5, 11}, {5, 12}}}, {1/2 (-1 - Sqrt[2]), {{1, 11}, {1, 12}, {2, 11}}}, {1 - Sqrt[2], {{7, 9}, {7, 10}}}, {1/2 (1 - Sqrt[2]), {{1, 9}, {1, 10}}}, {1/2 (-1 + Sqrt[2]), {{1, 7}, {1, 8}}}}

$\endgroup$
  • $\begingroup$ Thankxxx. It is very professional solution. Can you write the SortBy[N @* First] @ lst in a simpler way to understand how it does work. $\endgroup$ – Inzo Babaria May 16 at 10:04
  • $\begingroup$ I could not understand the mean of @* $\endgroup$ – Inzo Babaria May 16 at 10:05
  • 1
    $\begingroup$ @Inzo, it is short form for composition Composition[N, First], N@*First is the same function as N[First@#]&. $\endgroup$ – kglr May 16 at 10:12
6
$\begingroup$
list={{1/2 (-1 - Sqrt[2]), {{1, 11}, {1, 12}, {2, 11}}},{-1 - Sqrt[2], {{5, 11}, {5, 12}}},{1/2 (1 - Sqrt[2]), {{1, 9}, {1, 10}}}, {1 - Sqrt[2], {{7, 9}, {7, 10}}},{1/2 (-1 + Sqrt[2]), {{1, 7}, {1, 8}}}}   

SortBy[N@list,First]    

{{-2.41421, {{5., 11.}, {5., 12.}}}, {-1.20711, {{1., 11.}, {1., 12.}, {2., 11.}}}, {-0.414214, {{7., 9.}, {7., 10.}}}, {-0.207107, {{1., 9.}, {1., 10.}}}, {0.207107, {{1., 7.}, {1., 8.}}}}

$\endgroup$

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.