Efficient way to sum a product of numbers...

vsoler vicente.soler at gmail.com
Mon Aug 31 13:13:34 EDT 2009


On Aug 31, 6:59 pm, Tim Chase <python.l... at tim.thechases.com> wrote:
> vsoler wrote:
> > On Aug 31, 6:30 pm, Tim Chase <python.l... at tim.thechases.com> wrote:
> >>> After simplifying my problem, I can say that I want to get the sum of
> >>> the product of two culumns:
> >>> Say
> >>>          m= [[ 'a', 1], [ 'b', 2],[ 'a', 3]]
> >> assuming you meant ['c', 3] here...    ^>          r={'a':4, 'b':5, 'c':6}
>
> >>> What I need is the calculation
> >>>          1*4 + 2*5 + 3*4 = 4 + 10 + 12 = 26
> >> and you mean "3*6" here instead of "3*4", which is 18 instead of
> >> 12, making the whole sum 4+10+18=32
>
> >> Then it sounds like you could do something like
>
> >>   result = sum(v * r[k] for k,v in m)
>
> >> where "m" is any arbitrary iterable of tuples.  If the keys (the
> >> letters) aren't guaranteed to be in "r", then you can use
> >> defaults (in this case "0", but could just as likely be "1"
> >> depending on your intent):
>
> >>   result = sum(v * r.get(k,0) for k,v in m)
>
> >> If the conditions above don't hold, you'll have to introduce me
> >> to your new math. ;-)
> > There is no mistake in my original post, so I really meant [ 'a', 3]
>
> Ah...that makes more sense of the data.  My answer still holds
> then.  Use the r[k] version instead of the r.get(...) version,
> and it will throw an exception if the rate doesn't exist in your
> mapping.  (a KeyError if you want to catch it)
>
> -tkc

It works!!!

Thank you



More information about the Python-list mailing list