# Sorting upon the first element of a nested list and show that as numerical values

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.

• If you want to keep the exact forms of the first element you can use SortBy[lst, First[N[#]]&] – N.J.Evans May 16 '19 at 17:43

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}}}}

• Thankxxx. It is very professional solution. Can you write the SortBy[N @* First] @ lst in a simpler way to understand how it does work. – Inzo Babaria May 16 '19 at 10:04
• I could not understand the mean of @* – Inzo Babaria May 16 '19 at 10:05
• @Inzo, it is short form for composition Composition[N, First], N@*First is the same function as N[First@#]&. – kglr May 16 '19 at 10:12
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.}}}}