Inefficient summing

Matt Nordhoff mnordhoff at mattnordhoff.com
Thu Oct 9 03:40:18 EDT 2008


Chris Rebert wrote:
> I personally would probably do:
> 
> from collections import defaultdict
> 
> label2sum = defaultdict(lambda: 0)

FWIW, you can just use:

label2sum = defaultdict(int)

You don't need a lambda.

> for r in rec:
>     for key, value in r.iteritems():
>         label2sum[key] += value
> 
> ratio = label2sum["F1"] / label2sum["F2"]
> 
> This iterates through each 'r' only once, and (imho) is pretty
> readable provided you know how defaultdicts work. Not everything has
> to unnecessarily be made a one-liner. Coding is about readability
> first, optimization second. And optimized code should not be
> abbreviated, which would make it even harder to understand.
> 
> I probably would have gone with your second solution if performance
> was no object.
> 
> Cheers,
> Chris
-- 



More information about the Python-list mailing list