reduce函数常用来对序列求和,但是在使用过程中,出了点小问题
首先看一个正常的求和表达式:
reduce(lambda x,y:x+y,range(1,101)) #对1~100的数求和
如果我想求1~10的平方和呢:
reduce(lambda x,y:x**2+y**2,range(1,11))
运行后发现结果不对:
25800022600047052140012507345164607168429796314974446082384073840147073775468094045329287185417173482087059144697336379483484925016241871310518944097995034059103738852836322303863800321890406457125
那重新写一下:
it=[item for item in map(lambda x:x**2,range(1,11))]
reduce(lambda x,y:x+y,it)
这次结果为:385
为什么呢,为什么直接在lambda的retuen语句中做平方运算就错了呢?
这个问题正好让我更深入的理解了reduce函数的运算规则,我们来看一下reduce的官方解释:
reduce(…)
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
这里我把x+y的表达式换成x2+y2,calculates展开就是:
(((1+2)2+32)2+42)2+52。所以才得到了一个数字很大的结果。
回头看reduce函数的参数列表:(function,sequence),它的作用是对sequence中的元素按照function规定的运算输出。因此,如果我们要使用reduce函数时务必注意,操作元素在执行function操作前就计算完毕。