def calc_prod(lst):
def prod():
return reduce(lambda x, y : x * y, lst)
return prod
f = calc_prod([1, 2, 3, 4])
print f()
1 回答
已采纳
清波
TA贡献165条经验 获得超90个赞
官方解释如下:
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.
大致意思是,放入两个参数,一个是function, 另外一个是 可迭代对象,然后会返回用function 代入 可迭代对象后 的值。 类似官方解释中的案例:
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) ## 结果为 : ((((1+2)+3)+4)+5). 即: sum([1,2,3,4,5]), 列表各项的和
添加回答
举报
0/150
提交
取消