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
?
source to share
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).
source to share