finding items that occur more than once in a list
Arnaud Delobelle
arnodel at googlemail.com
Tue Mar 18 18:45:42 EDT 2008
On Mar 18, 9:56 pm, sturlamolden <sturlamol... at yahoo.no> wrote:
> On 18 Mar, 22:25, sturlamolden <sturlamol... at yahoo.no> wrote:
>
> > def nonunique(lst):
> > slst = sorted(lst)
> > return list(set([s[0] for s in
> > filter(lambda t : t[0] != t[1], zip(slst[:-1],slst[1:]))]))
>
> Obviously that should be 'lambda t : t[0] == t[1]'. Instead of using
> the set function, there is more structure to exploit when the list is
> sorted:
>
> def nonunique(lst):
> slst = sorted(lst)
> dups = [s[0] for s in
> filter(lambda t : t[0] == t[1], zip(slst[:-1],slst[1:]))]
> return [dups[0]] + [s[1] for s in
> filter(lambda t : t[0] != t[1], zip(dups[:-1],dups[1:]))]
Argh! What's wrong with something like:
def duplicates(l):
i = j = object()
for k in sorted(l):
if i != j == k: yield k
i, j = j, k
>>> list(duplicates([1, 2, 3, 2, 2, 4, 1]))
[1, 2]
--
Arnaud
More information about the Python-list
mailing list