If I have a list data_x = [1,2,3,4]
, how do I multiply each element of data_x
with each element of another list data_y = [2,3,4,5]
and sum the values?
The answer should be 1*2 +2*3 +3*4+ 4*5 = 40
. I am looking for some kind of for
loop.
If I have a list data_x = [1,2,3,4]
, how do I multiply each element of data_x
with each element of another list data_y = [2,3,4,5]
and sum the values?
The answer should be 1*2 +2*3 +3*4+ 4*5 = 40
. I am looking for some kind of for
loop.
Use zip
to perform index wise operations between two lists:
sum([x * y for x, y in zip(data_x, data_y)])
Or a numpy
solution using numpy.multiply
and numpy.sum
:
np.multiply(data_x, data_y).sum()
Try this (using a for loop, as requested by the OP):
answer = 0
for i in range(len(data_x)):
answer += (data_x[i] * data_y[i])
Another (quicker) way (using list
comprehensions):
answer = sum([x*y for x in zip(data_x, data_y)])
## Use zip to perform index-wise operations between two lists
## zip returns a list of tuples, with each tuple at index i containing the elements of data_x[i] and data_y[i]
You could also try this (if you have numpy
installed):
np.multiply(data_x, data_y).sum()
You can use zip
to do this.
data_x = [1, 2, 3, 4]
data_y = [2, 3, 4, 5]
res = sum([a * b for a, b in zip(data_x, data_y )])
print(res)
Use this
result = sum([x * y for x, y in zip(data_x, data_y)])
result = zip(data_x, data_y)
creates a zip object of tuples where each tuple result[i]
corresponds to the values data_x[i]
and data_y[i]
That is if
data_x = [1, 2, 3, 4]
data_y = [2, 3, 4, 5]
Then,
result = [(1, 2), (2, 3), (3, 4), (4, 5)]