[Tutor] Uniques values in a list
Alexandre Ratti
alex@gabuzomeu.net
Sun, 17 Mar 2002 14:20:50 +0100
Hi Sean,
At 07:45 16/03/2002 -0800, Sean 'Shaleh' Perry wrote:
[Filtering out unique values from a list:]
> > => Do you know any other solution (eg. using functional programming or
> > similar woodoo)?
>
>the "standard" approach is to sort the list, then walk it. You hold the first
>index in your hand and look at the second. If they match you dump the
>second and move on to the third. You continue until a non-match is
>found. you then hold the new item and look at the next one.
Thanks for this information. I guess this is the approach described in the
Python FAQ. Here is an example (slighty modified):
def filterList(theList):
if theList:
theList.sort()
last = theList[-1]
for i in range(len(theList) - 2, -1, -1):
if last == theList[i]:
del theList[i]
else:
last = theList[i]
return theList
if __name__ == "__main__":
toto = [1, 2, 2, 3, 4, 5, 3, 2, 7]
print filterList(toto)
>>> [1, 2, 3, 4, 5, 7]
>This is from the g++ 3.0 stl.
>
>void list::unique
>{
> iterator __first = begin();
> iterator __last = end();
> if (__first == __last) return;
> iterator __next = __first;
> while (++__next != __last) {
> if (*__first == *__next)
> erase(__next);
> else
> __first = __next;
> __next = __first;
> }
>}
One difference is that the Python example does a reverse loop, whereas your
code snippet loops from first to last, if I understand it correctly.
Cheers.
Alexandre