Re: How to select unique elements in a list?
- To: mathgroup at smc.vnet.net
- Subject: [mg8265] Re: How to select unique elements in a list?
- From: Robert Villegas <villegas>
- Date: Sat, 23 Aug 1997 01:59:03 -0400
- Organization: Wolfram Research
- Sender: owner-wri-mathgroup at wolfram.com
I am pretty sure that all the replies to this query > First, let me say that Union does not do what I'm looking for! I am > interested in a function which returns the unique elements from a list. > Let's call the function Distinct. Then, I want > > Distinct[{i1,i2,i3,i2}] > > to return > > {i1,i3} did not preserve the original ordering of the list when they extracted singletons. Although the original posting did not ask for this, some applications would want to retain the original order, so it's interesting to find a reasonably fast order-preserving version. We can build on the fast output of any of the proposed methods to fix up the ordering. First, a function that will reorder a subset according to the ordering of the original list: RestoreOrder[subset_, list_] := Last /@ Sort[ {Position[list, #, {1}, 1][[1, 1]], #}& /@ subset ] Now apply the RestoreOrder operator to any of the methods: Singletons[list_] := RestoreOrder[#, list]& @ Cases[Split @ Sort[list], {singleton_} :> singleton] Not as fast as the proposals, but it preserves more information. We might generalize this to selecting elements that occur k times instead of just once: MultiplicitySelect[list_, k_] := RestoreOrder[#, list]& [ First /@ Cases[Split @ Sort[list], Table[_, {k}] ] ] By the way, the same idea can produce an order-preserving variant of Union, which is something I've needed fairly frequently: EliminateRepetition[list_List] := RestoreOrder[Union[list], list] Robby Villegas