列表理解中的Python异常处理 [英] Python exception handling in list comprehension

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

问题描述

我有一个名为 plot_pdf(f)的Python函数,可能会导致错误。我使用列表解析来遍历此函数上的文件列表:

  [plot_pdf(f)for file in file_list] 

我想使用try-except块在迭代循环中跳过任何可能的错误,并继续下一个文件。以下代码是正确的方法来处理Python列表中的异常处理?

  try:
[plot_pdf f)for f in file_list]#using list comprehensions
except:
print(Exception:,sys.exc_info()[0])
continue

上述代码将终止当前的迭代并转到下一个迭代吗?如果我不能使用列表理解来捕获迭代中的错误,那么我必须使用正常的循环:

  for f in file_list:
try:
plot_pdf(f)
除了:
print(Exception:,sys.exc_info ()[0])
继续

我想知道我是否可以使用try-除了在列表理解中进行异常处理。

解决方案

  try:
[ print_pdf(f)for file in file_list]#using list comprehensions
except:
print(Exception:,sys.exc_info()[0])
continue

如果 plot_pdf(f)在执行理解期间抛出错误, ,它被捕获在,除了子句,理解的其他项目将不被评估。



它不是可能在列表解析中处理异常,因为列表的理解是一个包含其他表达式的表达式表达,没有更多(即函数调用是表达式,函数体可以包括所有的b $ b你想要的语句,所以将
异常容易的子表达式的评估委托给一个函数,如你所注意到的那样,是
一个可行的解决方法(其他的,在可行时,是检查

更多在这里


I have a Python function called plot_pdf(f) that might throw an error. I use a list comprehension to iterate over a list of files on this function:

[plot_pdf(f) for f in file_list]

I want to use try-except block to skip any possible errors during the iteration loop and continue with the next file. So is the following code correct way to do the exception handling in Python list comprehension?

try:
    [plot_pdf(f) for f in file_list]  # using list comprehensions
except:
    print ("Exception: ", sys.exc_info()[0])
    continue

Will the above code terminate the current iteration and go to the next iteration? If I can't use list comprehension to catch errors during iteration, then I have to use the normal for loop:

for f in file_list:
    try:
        plot_pdf(f)
    except:
        print("Exception: ", sys.exc_info()[0])
        continue

I want to know if I can use try-except to do exception handling in list comprehension.

解决方案

try:
    [plot_pdf(f) for f in file_list]  # using list comprehensions
except:
    print ("Exception: ", sys.exc_info()[0])
    continue

If plot_pdf(f) throws an error during execution of comprehension, then, it is caught in the except clause, other items in comprehension won't be evaluated.

It is not possible to handle exceptions in a list comprehension, for 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).

More here.

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

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