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 2004

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

Search the Archive

RE: Sort by buried element in list

  • To: mathgroup at
  • Subject: [mg48924] RE: [mg48899] Sort by buried element in list
  • From: "Wolf, Hartmut" <Hartmut.Wolf at>
  • Date: Thu, 24 Jun 2004 05:35:40 -0400 (EDT)
  • Sender: owner-wri-mathgroup at

>-----Original Message-----
>From: Steve Gray [mailto:stevebg at]
To: mathgroup at
>Sent: Tuesday, June 22, 2004 11:32 AM
>To: mathgroup at
>Subject: [mg48924] [mg48899] Sort by buried element in list
>	What's the best way to sort a multilevel list of the following
>type, using as the key the entries 065794, 205347, 000000, 004354,
>etc.? Of course I need all sublists sorted with the key. The entire
>list may be several thousand entries long. Speed is not much of a
>concern. The entries are computed one at a time, and the sort could be
>done at that time or all at once later. I need to (optionally) remove
>entries with duplicate keys, regardless of the other items in the
>entry. The position of the key is known beforehand (obviously).
>	The final result for this small sample would be
>	Thanks for any info.
>Steve Gray

be this your list:

In[1]:= ll =

Describe keyPos as the position specification (this is a sequence) of the key in each record:

In[2]:= keyPos = Sequence[-1,1];

In[3]:= Part[ll[[2]], keyPos]
Out[3]= 205347

This gives the keys of both, e.g. the second and third records:

In[4]:= Part[ll[[{2,3}]],{1,2}, keyPos]
Out[4]= {205347,0}

We pull out the expression for the List of the two records, by use of Function application:

In[5]:= Part[#,{1,2},-1,1]&[ll[[{2,3}]]]
Out[5]= {205347,0}

Transfering the (outer) List back to Part

In[6]:= Part[{##}, {1, 2}, keyPos] &[ll[[2]], ll[[3]]]
Out[6]= {205347,0}

Now applying OrderedQ gives the ordering function wanted for Sort 

In[8]:= OrderedQ[Part[{##}, {1, 2}, keyPos]] &[ll[[2]], ll[[3]]]
Out[8]= False

In[9]:= Sort[ll, OrderedQ[Part[{##}, {1, 2}, keyPos]] &]

For a different application just specify the appropriate keyPos.

Hartmut Wolf

  • Prev by Date: RE: Re: faster sublist checking
  • Next by Date: Seeking a compact expression in a model.
  • Previous by thread: Re: Sort by buried element in list
  • Next by thread: coupled eqns in NDSolve