I have two lists of fixed-length tuples. This function calculates a fraction (ratio) for respective elements (note, fX() does not use comprehension for readability here).
>>> def fX(a,b):
>>> c=[]
>>> for i in range(len(a)):
>>> c.append([a[i][x]/float(a[i][x]+b[i][x]) for x in range(len(a[i]))])
>>> return c
When all values are non-zero, fX() works:
>>> a[0]=(3, 4, 17, 9.6667, 6.6583, 0.4310, 1)
>>> b[0]=(4, 4, 12, 8.0, 3.2660, 0.0002, 1)
>>> fX(a,b)
>>> [[0.4286, 0.5, 0.5862, 0.5472, 0.6710, 0.9995, 0.5]]
However, when any pair’s values sum to zeros, fX() fails:
>>> a[0]=(3, 4, 17, 9.6667, 6.6583, 0.4310, 0)
>>> b[0]=(4, 4, 12, 8.0, 3.2660, 0.0002, 0)
>>> fX(a,b)
Traceback (most recent call last):
File "<pyshell#59>", line 1, in <module>
fX(a,b)
File "<pyshell#52>", line 4, in fX
c.append([a[i][x]/float(a[i][x]+b[i][x]) for x in range(len(a[i]))])
ZeroDivisionError: float division
I’m need a function, fY(), that gives this desired outcome without resorting to a brute force test of each value:
>>> a[i]=(3, 4, 17, 9.6667, 6.6583, 0.4310, 0)
>>> b[i]=(4, 4, 12, 8.0, 3.2660, 0.0002, 0)
>>> fY()
>>> [[0.4286, 0.5, 0.5862, 0.5472, 0.6710, 0.9995, 0.0]]
Thanks.
Use the
a if x else bternary operator (equivalent to the C/C++/Java expressionx ? a : b) to put the conditional inside the list comprehension. This gives an efficient, Pythonic implementation: