有人了解如何处理 map() 中的错误吗?我希望能够在程序不崩溃的情况下处理此类错误。
def add_one(val):
raise Exception('My error!')
return val+1
values = [1,2,3,4]
# Does not work
try:
new_values = map(add_one, values)
except:
new_values = []
print(list(new_values)) # Raises an Exception: My error!
# Works
try:
new_values = []
for x in values:
new_values.append(add_one(x))
except:
new_values = []
print(new_values) # Returns []
请您参考如下方法:
map 是惰性的 - 它在必要时才实际使用数据。
因此,您提供的两个示例并不等同。
