如何在Python中除以2的列表时处理List Comprehensions中的被零除的异常 [英] How to handle the divide by zero exception in List Comprehensions while dividing 2 lists in Python

查看:243
本文介绍了如何在Python中除以2的列表时处理List Comprehensions中的被零除的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Python中除以2个列表的同时处理List Comprehensions中的被零除异常:

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

从下面的示例中:

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

其中list2可以包含0作为值.

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.

推荐答案

您不能. try (compound)语句 ,列表理解是 表达式 .在Python中,这些是完全不同的东西,您不能在表达式中包含一条语句.

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

然后用作:

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".

您应该这样做:

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)))

这篇关于如何在Python中除以2的列表时处理List Comprehensions中的被零除的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆