[Tutor] Finding uniq. in lists
Daniel Yoo
dyoo@hkn.eecs.berkeley.edu
Thu, 10 May 2001 03:23:58 -0700 (PDT)
On Thu, 10 May 2001, Remco Gerlich wrote:
> On 0, steve <lonetwin@yahoo.com> wrote:
> > Hi all ye good people,
> > Ques: Is there a nice ( read good+clean+efficient ) way to do this:
> > I have a list p = ['foo', 'bar', 'foo-bar', 'foo', 'foo-bar' ]
> > I want the list to contain only single instances of elements, ie:I want to
> > filter out all the duplicate entries. This is the first thing that came to my
> > mind :
> > q = [ p[i] for i in range(len(p)) if p[i] not in p[(i+1):] ]
> > Prob. is I do not like it !! :) ...so either give me a better solu. or
> > convince me that the solu. I have is not bad :)
> That will be too slow. Use a dictionary, it's the fastest way:
>
> def uniq(q):
> dict = {}
> for s in q:
> dict[s] = 1
> return dict.keys()
Here's a hint of an alternative method. If you have the list
p = ['foo', 'bar', 'foo-bar', 'foo', 'foo-bar' ]
would your problem be easier if you rearranged the elements like this?
p_arranged = ['bar', 'foo', 'foo', 'foo-bar', 'foo-bar']