Lewistrick Lewistrick -4 years ago 103
Python Question

Preventing dividing by zero in list comprehensions

I have the following code:

scores = [confusion_matrix[idx][idx] / sum(confusion_matrix[idx]) for (idx, scores) in enumerate(confusion_matrix)]


My problem is that sum(confusion_matrix[idx]) could be 0 in some cases, resulting in a
ZeroDivisionError
. But because
confusion_matrix[idx][idx]
is also 0 in that case, I solved this as follows:

scores = [divide(confusion_matrix[idx][idx], sum(confusion_matrix[idx])) for (idx, scores) in enumerate(confusion_matrix)]


The function
divide(x,y)
returns 1 if
y==0
and
(x/y)
if
y>0
. But I wonder if there is an easier way. Maybe I could use some ternary operator, but does that exist in Python?

Answer Source

Yes, in python it's called the conditional expression:

[confusion_matrix[idx][idx] / sum(confusion_matrix[idx]) if sum(confusion_matrix[idx]) != 0 else 0 for (idx, scores) in enumerate(confusion_matrix)]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download