Counting things fast - was Re: Summing a 2D list

Paddy paddy3118 at googlemail.com
Thu Jun 12 20:07:43 CEST 2008


On Jun 12, 4:14 pm, Gerhard Häring <g... at ghaering.de> wrote:
> Aidan wrote:
> > does this work for you?
>
> > users = [1,1,1,2,2,3,4,4,4]
> > score = [0,1,5,3,1,2,3,3,2]
>
> > d = dict()
>
> > for u,s in zip(users,score):
> >   if d.has_key(u):
> >     d[u] += s
> >   else:
> >     d[u] = s
>
> > for key in d.keys():
> >   print 'user: %d\nscore: %d\n' % (key,d[key])
>
> I've recently had the very same problem and needed to optimize for the
> best solution. I've tried quite a few, including:
>
> 1) using a dictionary with a default value
>
> d = collections.defaultdict(lambda: 0)
> d[key] += value
>
<<SNIP>>
> -- Gerhard

This might be faster, by avoiding the lambda:

d = collections.defaultdict(int)
d[key] += value

- Paddy.



More information about the Python-list mailing list