Python:映射或压缩调用并忽略错误的最快方法是什么? [英] Python: what is the fastest way to map or compress calls and ignore errors?
问题描述
在python中快速跳过/处理错误的最佳方法是什么? >
例如,假设我有一个数据和一个函数的列表,该函数每当数据是一个str时会引发一个 ValueError
。我想要跳过这些值。一种方法是:
result = []
在数据中为n:
try :result.append(function(n))
除了ValueError:pass
你也可以做同样的事情没有错误检查像:
result = [function(n)for n in data]
或
result = list(map(function,data))
我想要一个c编译的方法来完成以上。
result = list(map(function,data,skip_errors = True))
default = value
的功能也很有用,错误创建一个默认值。
我认为这可能是我需要编写一个Cython扩展名。
注意:一个解决方案是让我写在 catch 函数 - 在c或cython中的 - exception-handling-in-list-comprehension?nah = 1#28816652>这个答案。然后我可以在列表压缩中使用它,并获得我想要的性能提升。
为什么不把你的函数包装在一个错误处理程序?
def spam(n):
try:
return function(n)
除了ValueError:
pass
result = [垃圾邮件(n)for数据]
你可以添加任何你想要的错误处理(请注意,在这个版本中,它返回无
,所以你可能想要过滤生成的列表或返回默认值)。使用 map
也是一样。
I frequently encounter a problem where I need to apply a function to a large iterator of data, but that function sometimes raises a known error that I want to ignore. Unfortunately, neither list compressions nor the map function has a good way to handle errors.
What is the best way to skip/deal with errors quickly in python?
For example, say I have a list of data and a function, the function raises a ValueError
whenever the data is a str. I want it to skip these values. One way to do this would be:
result = []
for n in data:
try: result.append(function(n))
except ValueError: pass
You could also do the same thing without the error checking like:
result = [function(n) for n in data]
or
result = list(map(function, data))
I want an c-compiled approach to accomplishing the above. Something in the spirit of
result = list(map(function, data, skip_errors=True))
The feature of default=value
would also be useful, so that raised errors create a default value.
I'm thinking this might be something I need to write a Cython extension for.
Note: one solution would be for me to write the catch
function I wrote in this answer in c or cython. Then I could use it in list compressions and get the performance boost I want.
Why not just wrap your function in an error handler?
def spam(n):
try:
return function(n)
except ValueError:
pass
result = [spam(n) for n in data]
you can then add anything you want to the error handling (note that in this version it returns None
, so you probably want to either filter the resulting list or return a default value). The same goes for using map
.
这篇关于Python:映射或压缩调用并忽略错误的最快方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!