Unpacking using a card

Assuming I have two iterables of numbers with the same length

weights = range(0, 10)
values = range(0, 100, 10)

      

I need to calculate a weighted amount. I know it can be done with a list comprehension.

weighted_sum = sum(weight * value for weight, value in zip(weights, values))

      

I wonder if this can be done using map

and operator.mul

eg

import operator

weighted_sum = sum(map(operator.mul, zip(weights, values)))

      

but this gives error

Traceback (most recent call last):
  File "<input>", line 3, in <module>
TypeError: op_mul expected 2 arguments, got 1

      

so my question is, is there a way to pass unpacked tuples using map

?

+3


source to share


3 answers


map

not needed zip

, just use

weighted_sum = sum(map(operator.mul, weights, values))

      

From map

Documentation

If additional iterative arguments are passed, the function must take many arguments and apply to elements from all iterations in parallel.

It is also mentioned in the documentation map

that instead of map

for, zip

you can use input itertools.starmap

instead map

.




As Rahul hinted , using is numpy

always a good idea when dealing with numbers, in fact something like

import numpy as np

np.asarray(weights) * values

      

should already be doing the trick (although unlike map

this requires the two arrays to be the same length, and map

display the shortest length).

+4


source


Try the following:

>>> import operator
>>>
>>> weights = range(0, 10)
>>> values = range(0, 100, 10)
>>> sum(map(lambda i:operator.mul(*i), zip(weights, values)))
2850

      



or

>>> sum(map(operator.mul, weights, values))
2850

      

+4


source


You can also try with numpy

,

In [45]: import numpy as np

In [46]: sum(map(np.multiply,weights,values))
Out[46]: 2850

      

As suggested by Tobias Kienzler,

In [52]: np.sum(np.array(weights) * values)
Out[52]: 2850

      

+2


source







All Articles