Sorting lists inside nested lists

I have a nested list: {{9, 8, 7}, {8, 7, 6}, {7, 6, 5}, {6, 5, 4}, {5, 4, 3}, {4, 3, 2}, {3, 2, 1}}

I need to sort the lists in a list in order to create:

{{7, 8, 9}, {6, 7, 8}, {5, 6, 7}, {4, 5, 6}, {3, 4, 5}, {2, 3, 4}, (1, 2, 3}}

How to do it?

+5
source share
2 answers

You need a function Mapthat applies a function to each element of the list.

That is, Map[f, {1, 2, 3}]it gives {f[1], f[2], f[3]}.

In this case you can use Map[Sort, list]. Mapalso has an infix operator /@:

In[1]:= Map[Sort, {{9, 8, 7}, {8, 7, 6}, {7, 6, 5}, {6, 5, 4}, 
  {5, 4, 3}, {4, 3, 2}, {3, 2, 1}}]

Out[1]= {{7, 8, 9}, {6, 7, 8}, {5, 6, 7}, {4, 5, 6},
  {3, 4, 5}, {2, 3, 4}, {1, 2, 3}}

In[2]:= Sort /@ {{9, 8, 7}, {8, 7, 6}, {7, 6, 5}, {6, 5, 4}, 
  {5, 4, 3}, {4, 3, 2}, {3, 2, 1}}

Out[2]= {{7, 8, 9}, {6, 7, 8}, {5, 6, 7}, {4, 5, 6}, 
  {3, 4, 5}, {2, 3, 4}, {1, 2, 3}}
+9
source

It may be helpful to know that the order will also work.

lst = {{9, 8, 7}, {8, 7, 6}, {7, 6, 5}, {6, 5, 4}, {5, 4, 3}, {4, 3, 
    2}, {3, 2, 1}};
Map[#[[Ordering[#]]] &, lst]

But for this type of example, the approach is slower than Map / Sort

lst2 = RandomInteger[100, {10^5, 3}];
Map[Sort, lst2]; // Timing
Map[#[[Ordering[#]]] &, lst2]; // Timing

{0.175955, Null}

{1.02087, Null}

An order may be useful for sorting by position.

lst3 = {{a1, 4, c1}, {a2, 3, c2}, {b3, 1, d3}, {e4, 2, f4}};
lst3[[Ordering[lst3[[All, -2]]]]] // MatrixForm

alt text

0
source

All Articles