Re: easiest way to sort a list?
- To: mathgroup at smc.vnet.net
- Subject: [mg18324] Re: [mg18308] easiest way to sort a list?
- From: Andrew Watson <abwatson at mail.arc.nasa.gov>
- Date: Sat, 26 Jun 1999 19:08:03 -0400
- Sender: owner-wri-mathgroup at wolfram.com
At 7:24 PM -0700 6/25/99, Peter T. Wang wrote:
> Suppose you have a list of integers, not all distinct,
>say
> {1, 5, 3, 5, 10, 10, 1},
>
>and you want to obtain the list
>
> {1, 5, 3, 10}
>
>which is the set of distinct elements but with the order preserved;
How about:
In[3]:=
in = {1, 5, 3, 5, 10, 10, 1};
In[4]:=
elements = Union[input]
Out[4]=
{1, 3, 5, 10}
In[12]:=
positions = Flatten[First[Position[in, #]] & /@ elements]
Out[12]=
{1, 3, 2, 5}
In[13]:=
in[[positions]]
Out[13]=
{1, 3, 5, 10}
or, in one step,
In[14]:=
OrderedUnion[list_] :=
list[[Flatten[First[Position[list, #]] & /@ Union[list]]]]
OrderedUnion[in]
Out[16]=
{3, 5, 7, 12}
Andrew B. Watson
MS 262-2
NASA Ames Research Center
Moffett Field, CA 94035-1000
(650) 604-5419 (650) 604-0255 fax
abwatson at mail.arc.nasa.gov http://vision.arc.nasa.gov/