Efficient way to sum a product of numbers...

Tim Chase python.list at tim.thechases.com
Mon Aug 31 18:30:27 CEST 2009


> 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. ;-)

-tkc






More information about the Python-list mailing list