reduce 函数是如何工作的? [英] How does reduce function work?
问题描述
据我所知,reduce 函数需要一个列表 l
和一个函数 f
.然后,它在列表的前两个元素上调用函数 f
,然后用下一个列表元素和前一个结果重复调用函数 f
.
As far as I understand, the reduce function takes a list l
and a function f
. Then, it calls the function f
on first two elements of the list and then repeatedly calls the function f
with the next list element and the previous result.
所以,我定义了以下函数:
So, I define the following functions:
以下函数计算阶乘.
def fact(n):
if n == 0 or n == 1:
return 1
return fact(n-1) * n
def reduce_func(x,y):
return fact(x) * fact(y)
lst = [1, 3, 1]
print reduce(reduce_func, lst)
现在,这不应该给我 ((1! * 3!) * 1!) = 6
吗?但是,它给出了 720
.为什么是 720
?它似乎也需要 6
的阶乘.但是,我需要了解原因.
Now, shouldn't this give me ((1! * 3!) * 1!) = 6
? But, instead it gives 720
. Why 720
? It seems to take the factorial of 6
too. But, I need to understand why.
有人可以解释为什么会发生这种情况以及解决方法吗?
Can someone explains why this happens and a work-around?
我基本上想计算列表中所有条目的阶乘乘积.备份计划是运行一个循环并计算它.但是,我更喜欢使用 reduce.
I basically want to compute the product of factorials of all the entries in the list. The backup plan is to run a loop and compute it. But, I would prefer using reduce.
推荐答案
好的,知道了:
我需要先将数字映射到它们的阶乘,然后使用乘法运算符调用 reduce.
I need to map the numbers to their factorials first and then call reduce with multiply operator.
所以,这行得通:
lst_fact = map(fact, lst)
reduce(operator.mul, lst_fact)
这篇关于reduce 函数是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!