在Python中的列表解析中如何处理异常? [英] How can I handle exceptions in a list comprehension in Python?

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

问题描述

我在Python中有一些列表解析,每次迭代都会抛出异常。



例如,如果我有:

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

[1 / egg for eggs in eggs]

我将在第3个元素中获得一个 ZeroDivisionError 异常。



如何处理这个异常并继续执行列表的理解?



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

  def spam(egg):
try:
return 1 / egg
除了ZeroDivisionError:
#handle除以零错误
#现在留空
pass

但是这对我来说看起来有点麻烦。



在Python中有没有更好的方法?



注意:这是一个简单的例子(请参见上面的em,例如),因为我的实例需要一些上下文。我没有兴趣避免除以零错误,而是在列表理解中处理异常。

解决方案

在Python中的表达式可以让您忽略异常(或者在异常情况下返回替代值和c),所以从字面上来说,处理列表推导中的异常是不可能的,因为列表解析是包含其他表达式的表达式,没有更多(即语句,只有语句可以捕获/忽略/处理异常)。



函数调用是表达式,函数体可以包括你想要的所有语句,所以将异常容易的子表达式的评估委托给一个函数(如你所注意到的)是一种可行的解决方法(其他的,在可行的时候,是检查可能引发异常的值,也如其他答案中的建议)。



正确的回答如何处理excep列表理解都表达了所有这些真理的​​一部分:1)字面上,即词汇在理解本身,你不能; 2)实际上,你可以将作业委托给一个函数,或者在可行的时候检查错误的值。你一再声称这不是答案是毫无根据的。


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

For instance, if I have:

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

[1/egg for egg in eggs]

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.

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.

解决方案

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

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.

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

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