MathGroup Archive 2005

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

Search the Archive

Re: Sorting nested list

  • To: mathgroup at smc.vnet.net
  • Subject: [mg57376] Re: [mg57295] Sorting nested list
  • From: "Wolf, Hartmut" <Hartmut.Wolf at t-systems.com>
  • Date: Thu, 26 May 2005 04:31:20 -0400 (EDT)
  • Sender: owner-wri-mathgroup at wolfram.com

 
>-----Original Message-----
>From: Gernot Pfanner [mailto:pfannerg at stud.uni-graz.at] 
To: mathgroup at smc.vnet.net
>Sent: Tuesday, May 24, 2005 11:13 AM
>Subject: [mg57376] [mg57295] Sorting nested list
>
>Hi!
>
>Please forgive me, if this is the 100.000th posting concerning 
>sorting a
>list. But at the moment I'm pretty confused, and so I ask you 
>kindly for
>your help...
>Given something like
>{{a,{2,4,1.,...}},{b,{3.2,-2,...}}}
>How do I sort just the inner lists (i.e. e.g. {2,4,1.,...}), so that my
>object finally looks like
>{{a,{1.,2,4.,...}},{b,{-2,3.2,...}}}
>In this spirit
>With thanks in advance
>Yours Gernot
>
>

Gernot,

in principle there are two complementary methods: 

First, dissect your expression, apply Sort to the parts intended and
recompose. 
Step by step, let

In[2]:=
l={{a,{2,4,1.,"..."}},{c,{3,1,2,"..."}},{b,{3.2,-2,"..."}}}


In[3]:= {keys, ll} = Transpose[l]
Out[3]=
{{a, c, b}, {{2, 4, 1., "..."}, {3, 1, 2, "..."}, {3.2, -2, "..."}}}


In[4]:= llsorted = Sort /@ ll
Out[4]=
{{1., 2, 4, "..."}, {1, 2, 3, "..."}, {-2, 3.2, "..."}}

In[5]:= Transpose[{keys, llsorted}]
Out[5]= 
{{a, {1., 2, 4, "..."}}, {c, {1, 2, 3, "..."}}, {b, {-2, 3.2, "..."}}}


Put together into a one-liner, (e.g., there are lots of variants):

In[7]:= Transpose[{#1, Sort /@ #2}]& @@ Transpose[l]
Out[7]=
{{a, {1., 2, 4, "..."}}, {c, {1, 2, 3, "..."}}, {b, {-2, 3.2, "..."}}}



Second, keep your structure untouched but map Sort to the right parts:

In[10]:= MapAt[Sort, l, Thread[{Range[Length[l]],2}]]
Out[10]=
{{a, {1., 2, 4, "..."}}, {c, {1, 2, 3, "..."}}, {b, {-2, 3.2, "..."}}}


(Of course you may combine both methods appropriately.)


--
Hartmut Wolf


  • Prev by Date: Re: Re: Nestwhile IHB
  • Next by Date: A.I for mathematica
  • Previous by thread: Re: Sorting nested list
  • Next by thread: Re: Sorting nested list