Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 within the list to create:

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

How do I do this?

like image 454
Ron Avatar asked Nov 19 '10 05:11

Ron


1 Answers

You want the Map function, which applies a function to each element of a list.

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

In this case, you can use Map[Sort, list]. Map also 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}}
like image 59
Michael Pilat Avatar answered Dec 31 '22 18:12

Michael Pilat