[Tutor] Handling Generator exceptions in Python 2.5

vince spicer vinces1979 at gmail.com
Fri Jun 19 17:09:08 CEST 2009


Well*

*result = [(ListA[i] - ListB[i-1])/ListA[i] for i in range(len(ListA))*if
not ListA[i] == 0*]

will exclude any results where listA[i] is 0, if you still want these in the
result
you may want to use good'ol for statement instead of list comprehension


results = []
for x in range(len(listA)):
    y = ListA[i] - ListB[i-1]
    if not ListA[i] == 0:
        y = y / ListA[i]
    results.append(y)

print results

Vince


On Fri, Jun 19, 2009 at 8:55 AM, Joe Python <jopython at gmail.com> 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
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090619/2eb35c59/attachment.htm>


More information about the Tutor mailing list