Вопрос

Is there a way to ignore values in a list that create a division by zero in an iterative script instead of removing those problem values?

I'm thinking along the lines of if

if(x==0):
 break
elif(x!=0):
 continue

Where the values that aren't zero get to continue on through the script.

Это было полезно?

Решение

You can use list comprehension for a more efficient code,

from __future__ import division
num = [1,2,3,4,5,6,3,31,1,0,120,0,0]
divisor = 10
print [divisor/x for x in num if x != 0]

Output:

[10.0, 5.0, 3.3333333333333335, 2.5, 2.0, 1.6666666666666667, 3.3333333333333335, 0.3225806451612903, 10.0, 0.08333333333333333]

Другие советы

Of course. You can do what you did creating a if this, then that. Or you could even set up a try/except loop and catch the division by zero exception.

A trivial example -

>>> d = [1,0,3,4,5,6,0]
>>> for x in d:
...    if x == 0: 
...        continue  # skip this number since it will error.
...    print (5 / x)
... 
5
1
1
1
0

If you're doing a lot of arithmetic on arrays, you may want to consider using numpy. On top of being easier to use, and usually much faster, it's also more flexible.

For example:

>>> divisors = np.array([1,2,3,4,5,6,3,31,1,0,120,0,0])
>>> fractions = 10. / divisors
>>> fractions
array([ 10.        ,   5.        ,   3.33333333,   2.5       ,
         2.        ,   1.66666667,   3.33333333,   0.32258065,
        10.        ,          inf,   0.08333333,          inf,          inf])

Compare to:

>>> fractions = []
>>> for divisor in divisors:
...     if divisor == 0:
...         fractions.append(float('inf'))
...     else:
...         fractions.append(10. / divisor)

Or even:

>>> fractions = [10. / divisor if divisor else float('inf') 
...              for divisor in divisors]

numpy isn't always the answer, but it's worth taking a look at.

The best way should be to use exception handling to just show an error message.

    try:
        foo_with_possible_division_by_zero()
    except ZeroDivisionError:
        print "Warning: NaN encountered!"

If you do not want a message just replace the print statement with pass

The easiest way to ignore zero divisions I think can be done arithmetically by simply adding a small decimal to the divisor.

eg. if g = 0 and you want to compute g/g. you can get around that this way:

g/(g+0.0000001) The best thing about this is you will get your computation to behave algebraically similar to 0/0 = 0

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top