如何处理列表推导式中的异常? [英] How to handle exceptions in a list comprehensions?
问题描述
我在 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屋!