Python:如何管理ZeroDivisionError

时间:2017-05-20 10:44:54

标签: python python-2.7

我对Python很陌生,我正在努力解决这个错误,这是我的代码:

new_dictionary = dict(((i,f), abs(int(-d/-(-first_dictionary[i, f]//second_dictionary[i, f])))) for i in I for f in F)

我得到了回报:ZeroDivisionError: float division by zero

我知道发生此错误是因为first_dictionary和second_dictionary的某些值等于0.0,但我不知道如何管理它。

我试图定义这个函数:

def my_function(dict1, dict2):
    first_dictionary = dict1
    second_dictionary = dict2
    for i in I:
        for f in F:
            if first_dictionary[i, f] == 0 or second_dictionary[i, f] == 0.0:
                new_value = 0
            else:
                new_value = abs(int(-d/-(-first_dictionary[i, f]//second_dictionary[i, f])))
    return new_value


new_dictionary = dict(((i, f), my_function(first_dictionary, second_dictionary)) for i in I for f in F)

但输出与我的预期不同,它为字典中的所有键提供了相同的值。

如何解决此错误?提前谢谢!

2 个答案:

答案 0 :(得分:1)

来源 - Reference

>>> try:
    ...     f(0)
    ... except ZeroDivisionError:
    ...     import traceback
    ...     traceback.print_last()
    ... 
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>

您可以使用它来检查导致错误的第一个实例

答案 1 :(得分:1)

如果要进行显式检查而不是错误捕获,则不需要执行两个循环:

def safe_division(a, b):
    if not b:
        return 0
    return a / b

new_dictionary = dict(((i,f), abs(int(safe_division(-d, safe_division(-first_dictionary[i, f], second_dictionary[i, f]))))) for i in I for f in F)

实际上,让我们用dict理解让它变得更好一点:

new_dictionary = {(i, f): abs(int(safe_division(-d, safe_division(-first_dictionary[i, f], second_dictionary[i, f])))) for i in I for f in F}