如何处理列表推导中的异常? [英] How to handle exceptions in a list comprehensions?

查看:75
本文介绍了如何处理列表推导中的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python中有一些列表理解,其中每次迭代都可能引发异常.

I have some a list comprehension in Python in which each iteration can throw an exception.

例如,如果我有

eggs = (1,3,0,3,2)

[1/egg for egg in eggs]

我将在第三个元素中得到一个ZeroDivisionError异常.

I'll get a ZeroDivisionError exception in the 3rd element.

如何处理此异常并继续执行列表理解?

How can I handle this exception and continue execution of the list comprehension?

我唯一想到的方法是使用辅助函数:

The only way I can think of is to use a helper function:

def spam(egg):
    try:
        return 1/egg
    except ZeroDivisionError:
        # handle division by zero error
        # leave empty for now
        pass

但这对我来说有点麻烦.

But this looks a bit cumbersome to me.

在Python中有更好的方法吗?

Is there a better way to do this in Python?

注意:这是我做的一个简单示例(请参见上面的"例如"),因为我的实际示例需要一些上下文.我对避免除以零错误不感兴趣,但对处理列表理解中的异常不感兴趣.

Note: This is a simple example (see "for instance" above) that I contrived because my real example requires some context. I'm not interested in avoiding divide by zero errors but in handling exceptions in a list comprehension.

推荐答案

Python中没有内置表达式可让您忽略异常(或在出现异常的情况下返回备用值& c),因此这是不可能的,从字面上来讲,处理列表推导中的异常"是因为列表推导是一个包含其他表达式的表达式,仅此而已(即, no 语句,只有语句可以捕获/忽略/处理异常).

There is no built-in expression in Python that lets you ignore an exception (or return alternate values &c in case of exceptions), so it's impossible, literally speaking, to "handle exceptions in a list comprehension" because a list comprehension is an expression containing other expression, nothing more (i.e., no statements, and only statements can catch/ignore/handle exceptions).

函数调用是表达式,函数主体可以包含您想要的所有语句,因此,正如您所注意到的,将易于发生异常的子表达式的评估委托给函数是一种可行的解决方法(其他方法是可行的方法是检查可能引起异常的值,如其他答案中所建议的那样.

Function calls are expression, and the function bodies can include all the statements you want, so delegating the evaluation of the exception-prone sub-expression to a function, as you've noticed, is one feasible workaround (others, when feasible, are checks on values that might provoke exceptions, as also suggested in other answers).

对如何处理列表理解中的异常"这一问题的正确回答都表达了所有上述事实的一部分:1)从字面上,即从词法上讲,理解本身不能; 2)实际上,在可行的情况下,您将作业委派给某个函数或检查易于出错的值.您一再声称这不是答案,这是没有根据的.

The correct responses to the question "how to handle exceptions in a list comprehension" are all expressing part of all of this truth: 1) literally, i.e. lexically IN the comprehension itself, you can't; 2) practically, you delegate the job to a function or check for error prone values when that's feasible. Your repeated claim that this is not an answer is thus unfounded.

这篇关于如何处理列表推导中的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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