MathGroup Archive 2005

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

Search the Archive

Re: Sorting nested list


"plizak" <plizak at gmail.com> wrote in message 
news:d76o0i$7mu$1 at smc.vnet.net...
>I have a similar problem, I need to sort the same kind of list
>
> {{a,{2,4,1.,...}}, {c, {1,2,...}},{b,{3.2,-2,.­..}}}
>
> but I need to sort it based on the first element of each subarray,
> while keeping the second element the same.
>
> I did a pretty ugly solution (like 12 lines of code).  Is there a
> quicker more elegant way to sort this?
>

The simplest idea is to use Sort with an ordering function. An alternate 
idea, which is in general much quicker, is to generate a key for each 
element in the array, and then use Ordering on this list of keys. In your 
case, we would do the following:

In[12]:=
data = {{a, {2, 4, 1.}}, {c, {1, 2}}, {b, {3.2, -2}}};
keys = data[[All, 2, 1]]
Out[13]=
{2, 1, 3.2}

Then, use Ordering to get the sorted list:

In[14]:=
data[[Ordering[keys]]]
Out[14]=
{{c, {1, 2}}, {a, {2, 4, 1.}}, {b, {3.2, -2}}}

Let's compare the timing for this approach versus using Sort with an 
ordering function:

data = Table[{Random[], Table[Random[], {10}]}, {10^5}];

In[16]:=
r1 = data[[Ordering[data[[All, 2, 1]]]]]; // Timing
r2 = Sort[data, #2[[2, 1]] > #1[[2, 1]] &]; // Timing
r1 === r2
Out[16]=
{0.157 Second, Null}
Out[17]=
{6.343 Second, Null}
Out[18]=
True

We see that the Ordering approach is about 40 times faster for this data 
set.

Carl Woll 



  • Prev by Date: Re: Re: Printing - mathematica cropping the right hand side... :(
  • Next by Date: Re: global fit
  • Previous by thread: Re: Sorting nested list
  • Next by thread: Applying a list of functions to a list of arguments