发生的情况是,在某一时刻 math.log10() 被调用一个负值,这会触发域错误。请记住,reduce 的第一遍使用 x 和 y 的可迭代的前两个值(假设没有初始化器)。但是,在每个后续传递中,x 代表上一个 lambda 调用返回的值,y 是迭代中的下一个值。
例子:
from functools import reduce
import math
def do_log10(x, y):
print(f"x:{x:>5.2f}, y:{y:>5.2f}")
return math.log10(x) + math.log10(y)
nums_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
nums_log_fac = reduce(do_log10, nums_list)
print (nums_log_fac)
输出:
x: 1.00, y: 2.00
x: 0.30, y: 3.00
x:-0.04, y: 4.00
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-25-2bec9dea93b2> in <module>
7
8 nums_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
----> 9 nums_log_fac = reduce(do_log10, nums_list)
10 print (nums_log_fac)
<ipython-input-25-2bec9dea93b2> in do_log10(x, y)
4 def do_log10(x, y):
5 print(f"x:{x:>5.2f}, y:{y:>5.2f}")
----> 6 return math.log10(x) + math.log10(y)
7
8 nums_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
ValueError: math domain error