mardi 1 décembre 2015

Alternative to if statement to avoid division by zero or empty list?

Right now, in my code I have two lines. aboveAdj1 and aboveAdj2 are lists that contain 1s and 0s, or are empty:

if len(aboveAdj1) and len(aboveAdj2):
    perAboveFix = 100*int(sum(aboveAdj1) + sum(aboveAdj2))/int(len(aboveAdj1) + len(aboveAdj2))

If both aboveAdj1 and aboveAdj2 are not empty or all zeros, then calculate the ratio. Is there an efficient/short way of calculating the ratio based on only one of the variables, if the other variable is empty, without having to write a bunch of if statements?

For example, if aboveAdj1 is empty or all zeros, then calculate:

perAboveFix = 100*int(sum(aboveAdj2))/int(len(aboveAdj2))

and visa-versa.

Aucun commentaire:

Enregistrer un commentaire