How do I divide by the corresponding element in the list while using zip()
Problem Description:
I am trying to find out how can I do (i1+i2)/[i]
for the ith element before getting the mean.
import numpy as np
def avg_prod(l1, l2):
np.mean([i1 * i2 for i1, i2 in zip(l1, l2)])
I tried to use i
inside the code, but it produces an error.
Solution – 1
You can use enumerate
:
def avg_prod(l1, l2):
np.mean([i1 * i2 / i for i, (i1, i2) in enumerate(zip(l1, l2))])
or iterate over indices:
def avg_prod(l1, l2):
np.mean([l1[i] * l2[i] / i for i in range(min(len(l1), len(l2)))])
you can minimize it in case you are sure that the lengths of the lists are equal:
def avg_prod(l1, l2):
np.mean([l1[i] * l2[i] / i for i in range(len(l1))])