RE: Sort List of Lists
- To: mathgroup at smc.vnet.net
- Subject: [mg24827] RE: [mg24809] Sort List of Lists
- From: "Tomas Garza" <tgarza at mail.internet.com.mx>
- Date: Sun, 13 Aug 2000 23:49:53 -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. More on the subject. If you are really keen to use pure functions, take a look at the definition of Sort: "Sort[list, p] applies the function p to pairs of elements in list to determine whether they are in order. The default function p is OrderedQ[{#1, #2}]&". Now you want to compare pairs of sub-lists in your list a according to the second element in each sublist. Your ordering function must give True if the second element in the first sub-list is greater than or equal to the second element in the second sub-list, right? This translates as GreaterEqual[#1[[2]], #2[[2]]] &, so that In[1]:= a Out[1]= {{9, 2}, {1, 6}, {2, 4}} In[2]:= Sort[a, GreaterEqual[#1[[2]], #2[[2]]] &] Out[2]= {{1, 6}, {2, 4}, {9, 2}} Tomas Garza Mexico City