Mathematica 9 is now available
Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2005
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2005

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

Search the Archive

Re: Sorting nested list

  • To: mathgroup at smc.vnet.net
  • Subject: [mg57476] Re: Sorting nested list
  • From: "Carl K. Woll" <carlw at u.washington.edu>
  • Date: Sun, 29 May 2005 01:03:34 -0400 (EDT)
  • Organization: University of Washington
  • References: <d6us0f$ivm$1@smc.vnet.net> <d76o0i$7mu$1@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

"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