finding items that occur more than once in a list
Chris
cwitts at gmail.com
Tue Mar 18 06:18:20 EDT 2008
On Mar 18, 11:57 am, Simon Forman <sajmik... at gmail.com> wrote:
> Is there a more efficient way to do this?
>
> def f(L):
> '''Return a set of the items that occur more than once in L.'''
> L = list(L)
> for item in set(L):
> L.remove(item)
> return set(L)
>
> |>> f([0, 0, 1, 1, 2, 2, 3])
> set([0, 1, 2])
def f(L):
D = dict()
for item in L:
if item in D:
D[item] += 1
else:
D[item] = 1
return [i for i,j in D.items() if j > 1]
That would be my way to do it, would need to test it via several
thousand iterations to see which one is most efficient though.
More information about the Python-list
mailing list