MathGroup Archive 2011

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Sorting nested lists with strings

  • To: mathgroup at smc.vnet.net
  • Subject: [mg116287] Re: Sorting nested lists with strings
  • From: "Sjoerd C. de Vries" <sjoerd.c.devries at gmail.com>
  • Date: Thu, 10 Feb 2011 05:20:14 -0500 (EST)
  • References: <iitejq$jib$1@smc.vnet.net>

I'm not sure why you think Sort sorts on the second field of the list.
It doesn't:

In[534]:= list = {{"Paul", 23}, {"Amanda", 5}, {"Carl", 32}};

In[535]:= Sort[list]

Out[535]= {{"Amanda", 5}, {"Carl", 32}, {"Paul", 23}}



If you'd like to sort on another field (say the second) you could
change the ordering function of Sort or change a similar function in
Sortby (check the documentation; Sort and SortBy use slightly
different principles):

In[536]:= Sort[list, OrderedQ[{#1[[2]], #2[[2]]}] &]

Out[536]= {{"Amanda", 5}, {"Paul", 23}, {"Carl", 32}}

In[537]:= SortBy[list, #[[2]] &]

Out[537]= {{"Amanda", 5}, {"Paul", 23}, {"Carl", 32}}

Cheers -- Sjoerd

On Feb 9, 8:09 am, Paperorbifold <kgodelNOS... at liberoNOSPAM.it> wrote:
> I've a nested list of this kind:
> list={{"Paul",23},{"Amanda",55},{"Carl",32},...}
> Suppose I want to perform an alphabetic sort on the first element. Which is
> the condition I've to write in Sort[list,...]?
> Actually Sort[list] automatically operates on the second element.
> Thanks.
>
> --
> ...and I will make them pay for\nwhat they've done! (J.L. Picard)



  • Prev by Date: Apply a rule to an expression only once
  • Next by Date: Re: Another point about Mathematica 8.0
  • Previous by thread: Re: Sorting nested lists with strings
  • Next by thread: Re: Sorting nested lists with strings