RE: easiest way to sort a list?
- To: mathgroup at smc.vnet.net
- Subject: [mg18323] RE: [mg18308] easiest way to sort a list?
- From: "Ersek, Ted R" <ErsekTR at navair.navy.mil>
- Date: Sat, 26 Jun 1999 19:08:02 -0400
- Sender: owner-wri-mathgroup at wolfram.com
Peter (peterw at cco.caltech.edu) 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; i.e.,
the order in which the elements in the second list appear is the same as
the order in which it first occurs in the first list. What is a simple
way to do this? Evidently Union[] sorts the elements in canonical order,
which is not desirable. My current solution is so messy that I suspect
there must be an easier way.
------------------------
Peter,
Robby Villegas posted a slick solution to this problem in this newsgroup.
See [mg8265] from 23, August 1997.
-----------------------
In[1]:=
RestoreOrder[subset_, list_] := Last /@ Sort[ {Position[list, #, {1}, 1][[1,
1]], #}& /@ subset ] ;
EliminateRepetition[list_List] := RestoreOrder[Union[list], list]
In[3]:=
EliminateRepetition[{1,5,3,5,10,10,1}]
Out[3]=
{1,5,3,10}
This works for any list, not just a list of integers, numbers, etc.
Regards,
Ted Ersek