Re: Keeping order with Union
- To: mathgroup at smc.vnet.net
- Subject: [mg32612] Re: [mg32590] Keeping order with Union
- From: Tomas Garza <tgarza01 at prodigy.net.mx>
- Date: Thu, 31 Jan 2002 01:45:44 -0500 (EST)
- References: <200201300819.DAA29991@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
I guess this problem has been posed before in this forum, and many answers
must have been put forward. Anyway, being too lazy to search in the
archives, I propose the following. Let lst be your list, from which you wish
to eliminate duplicates, preserving the order. Define the function elimReps:
In[1]:=
elimReps[u_, v_] := If[MemberQ[u, v], u, Append[u, v]]
Then use Fold on your list as follows:
In[2]:=
Fold[elimReps, {First[lst]}, Rest[lst]]
Examples:
In[3]:=
list1={a, b, c, e, e, g, a, 1, 5, 1, b};
In[4]:=
Fold[elimReps, {First[list1]}, Rest[list1]]
Out[4]=
{a, b, c, e, g, 1, 5}
In[5]:=
list2 = Table[Random[Integer, {0, 9}], {10}]
Out[5]=
{0, 9, 8, 3, 0, 7, 3, 6, 4, 2}
In[6]:=
Fold[elimReps, {First[list2]}, Rest[list2]]
Out[6]=
{0, 9, 8, 3, 7, 6, 4, 2}
Tomas Garza
Mexico City
----- Original Message -----
From: "Dave Snead" <dsnead6 at charter.net>
To: mathgroup at smc.vnet.net
Subject: [mg32612] [mg32590] Keeping order with Union
> I'd like a function that throws out duplicate entries in a list and keeps
> the
> original list order. (when it sees 2 equal entries it throws out the one
> that is later in the list). I'd use Union, but it sometimes changes the
> order of the elements in the list. What's the tersest way to do this?
> Thanks in advance,
> Dave Snead
>
>
>
>
>
- References:
- Keeping order with Union
- From: "Dave Snead" <dsnead6@charter.net>
- Keeping order with Union