How to handle the divide by zero exception in List Comprehensions while dividing 2 lists in Python

♀尐吖头ヾ 提交于 2019-12-06 02:39:10

问题


How to handle the divide by zero exception in List Comprehensions while dividing 2 lists in Python:

From below example:

from operator import truediv
result_list = map(truediv, [i for i in list1], [j for j in list2])

where the list2 can contain the 0 as value.

I want to handle the exception in the same line due to my code constrain. Please help me.


回答1:


You cannot. try is a (compound) statement, a list-comprehension is an expression. In Python these are completely distinct things and you cannot have a statement inside an expression.

The thing you can do is using a wrapper function:

def add_handler(handler, exc, func):
    def wrapper(*args, **kwargs):

        try:
            return func(*args, **kwargs)
        except exc:
            return handler(*args, **kwargs)    # ???
    return wrapper

Then used as:

my_truediv = add_handler(print, ZeroDivisionError, truediv)

Note that this is very limited. You must return a value and insert it into the resulting list, you can't simply "skip it".

You should simply do:

from operator import truediv
result_list = []
for i, j in zip(list1, list2):
    try:
        result_list.append(i/j)
    except ZeroDivisionError:
        pass

Alternatively, if you simply want to skip those values you can just filter them out:

map(lambda x_y: truediv(*x_y), filter(lambda x_y: x_y[1] != 0, zip(list1, list2)))



回答2:


If you want to record the divisions by zero as NaN then you could use your own custom division function as follows:

import numpy as np

def divide(a, b):
    if b == 0:
        return np.nan
    else: 
        return a/b

list1 = [1, 2, 3]
list2 = [1, 0, 2]
result_list = map(divide, [i for i in list1], [j for j in list2])



回答3:


You could easily filter out 0 values like so,

from operator import truediv
result_list = map(truediv, [i for i in list1], [j for j in list2 if j])


来源:https://stackoverflow.com/questions/32308335/how-to-handle-the-divide-by-zero-exception-in-list-comprehensions-while-dividing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!