[Tutor] Handling Generator exceptions in Python 2.5
Dave Angel
davea at ieee.org
Fri Jun 19 20:34:04 CEST 2009
Joe Python wrote:
> I have a generator as follows to do list calculations.
>
> *result = [(ListA[i] - ListB[i-1])/ListA[i] for i in range(len(ListA))]*
>
> The above generator, throws '*ZeroDivisionError*' exception if ListA[i] =
> 0.
> Is there a way to say 'Don't divide by ListA[i] if its equal to 0 (within
> that statement)'.
>
> Sorry if this question sounds too stupid.
>
> TIA
> Joe
>
Doesn't sound stupid to me at all.
Short answer is a conditional expression. Replace
(ListA[i] - ListB[i-1])/ListA[i]
with
(ListA[i] - ListB[i-1])/ListA[i] if ListA[i] else 1.0
and you'll see 1.0 whenever ListA[i] == 0, and your original value
otherwise.
But I see a couple of other things. You're calling this a generator
when it's a list comprehension. For short lists, that frequently
doesn't matter, but in case it does, you could start by replacing the
braces on the outside with parentheses.
Next question is the two lists are the same length. And final one is
whether you really meant the offset of one when accessing ListB. If the
lists are both of length 4, you're doing something like
(a0 - b3)/a0 (a1-b0)/a1 (a2-b1)/a2 (a3-b2)/a3
In other words, you're using the last item of ListB for the first division.
If that's really what you want, consider the following generator:
gen = ((a-b)/a if a!=0.0 else 1.0 for a,b in zip(ListA, ListB[-1:]+ListB))
More information about the Tutor
mailing list