computing a weighted sum
Will McGugan
news at NOwillmcguganSPAM.com
Wed Mar 16 09:56:39 EST 2005
andreif at mail.dntis.ro wrote:
> Suppose I have a list of n floats x and a list of n floats w and I want
> to compute x[0]*w[0] + .. + x[n-1]*w[n-1].
>
> Is there some elegant expression (perhaps using lambda) to have it done
> in one statement ? As in :
> y = lambda x,w : ...
>
> I ask because the way I am doing it now :
> y = 0
> for i in range(0,n): y += x[i]*w[i]
>
> doesn't seem very pythonic :)
>
I'll take a stab at that!
In Python 2.3
sum( [ _x * _w for _x, _w in zip( x, w ) ] )
or in 2.4
sum( _x * _w for _x, _w in zip( x, w ) )
You may want to use itertools.izip in place of zip if the lists are large.
Will McGugan
More information about the Python-list
mailing list