RE: Sort List of Lists
- To: mathgroup at smc.vnet.net
- Subject: [mg24826] RE: [mg24809] Sort List of Lists
- From: "Tomas Garza" <tgarza at mail.internet.com.mx>
- Date: Sun, 13 Aug 2000 23:49:50 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
Dana wrote: > Hello. Could someone please give me a clue on how to sort a list based on > the Second Element in a List: > I think one needs to use a "pure function" but I am too new with > Mathematica (v4) > (Trying to learn though) :>) > > For Example, I would like to sort this list based on the second element in > each sub-list in "Descending" order: > > {{9, 2}, {1, 6}, {2, 4}} > > Results would be: > { {1,6},{2,4},{9,2} } > > > I think I will learn a lot about Lists, Sorting, and Pure Functions all in > one shot if I could get a hint on how to do this. Trying to learn all those things in one shot may be too much. Stick to Lists and Sorts for the time being. Recall that Sort uses canonical order as a default, and that means using the first element of each sub-list as ordering criterion. If you first reverse the order of the sub-lists and then sort, and then reverse the order of the sub-lists in the resulting list, you get the result in ascending order. Reverse this to get the result in descending order. Finally, reverse each sub-list again. E.g. In[1]:= a = {{9, 2}, {1, 6}, {2, 4}} In[2]:= Reverse /@ (Reverse /@ a // Sort // Reverse) Out[2]= {{1, 6}, {2, 4}, {9, 2}} I hope this is not too confusing. Step by step: In[3]:= Reverse /@ a Out[3]= {{2, 9}, {6, 1}, {4, 2}} Now you use Sort and get (in ascending order by the second element): In[4]:= Sort[{{2, 9}, {6, 1}, {4, 2}}] Out[4]= {{2, 9}, {4, 2}, {6, 1}} Using Reverse on this list gets the sort in descending order: In[5]:= Reverse[{{2, 9}, {4, 2}, {6, 1}}] Out[5]= {{6, 1}, {4, 2}, {2, 9}} Finally, reverse each sub-list: In[6]:= Reverse /@ {{6, 1}, {4, 2}, {2, 9}} Out[6]= {{1, 6}, {2, 4}, {9, 2}} A more general approach - assuming your sub-lists have more than two elements each - and you might want to use the n-th one as sorting criterion would use RotateLeft and RotateRight instead of simply Reverse: In[7]:= RotateRight[#, 1] & /@ (RotateLeft[#, 1] & /@ a // Sort // Reverse) Out[7]= {{1, 6}, {2, 4}, {9, 2}} Tomas Garza Mexico City