Services & Resources / Wolfram Forums
MathGroup Archive
*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
  • Subject: [mg57476] Re: Sorting nested list
  • From: "Carl K. Woll" <carlw at>
  • Date: Sun, 29 May 2005 01:03:34 -0400 (EDT)
  • Organization: University of Washington
  • References: <d6us0f$ivm$> <d76o0i$7mu$>
  • Sender: owner-wri-mathgroup at

"plizak" <plizak at> wrote in message 
news:d76o0i$7mu$1 at
>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:

data = {{a, {2, 4, 1.}}, {c, {1, 2}}, {b, {3.2, -2}}};
keys = data[[All, 2, 1]]
{2, 1, 3.2}

Then, use Ordering to get the sorted list:

{{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}];

r1 = data[[Ordering[data[[All, 2, 1]]]]]; // Timing
r2 = Sort[data, #2[[2, 1]] > #1[[2, 1]] &]; // Timing
r1 === r2
{0.157 Second, Null}
{6.343 Second, Null}

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

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