Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I divide by the corresponding element in the list while using zip()

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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))])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading