问题描述
在Python 3.3中, itertools.accumulate()
反复对提供的可迭代对象执行加法运算,现在可以将函数参数用作参数;这意味着它现在与 functools.reduce()
重叠.粗略地看,两者之间的主要区别现在似乎是:
In Python 3.3, itertools.accumulate()
, which normally repeatedly applies an addition operation to the supplied iterable, can now take a function argument as a parameter; this means it now overlaps with functools.reduce()
. With a cursory look, the main differences between the two now would seem to be:
-
accumulate()
默认为求和,但不允许您显式提供额外的初始条件,而reduce()
没有默认为任何方法,但允许您提供用于1/0元素序列的初始条件,和 -
accumulate()
首先采用可迭代,而reduce()
首先采用该函数.
accumulate()
defaults to summing but doesn't let you supply an extra initial condition explicitly whilereduce()
doesn't default to any method but does let you supply an initial condition for use with 1/0-element sequences, andaccumulate()
takes the iterable first whilereduce()
takes the function first.
两者之间还有其他区别吗?还是这只是两个功能的行为问题,最初具有不同用途的功能开始逐渐融合?
Are there any other differences between the two? Or is this just a matter of behavior of two functions with initially distinct uses beginning to converge over time?
推荐答案
似乎accumulate
保留了先前的结果,而reduce
(在其他语言中称为fold)则不一定.
It seems that accumulate
keeps the previous results, whereas reduce
(which is known as fold in other languages) does not necessarily.
例如list(accumulate([1,2,3], operator.add))
将返回[1,3,6]
,而普通折叠将返回6
e.g. list(accumulate([1,2,3], operator.add))
would return [1,3,6]
whereas a plain fold would return 6
(出于娱乐目的,请勿这样做)您可以根据reduce
Also (just for fun, don't do this) you can define accumulate
in terms of reduce
def accumulate(xs, f):
return reduce(lambda a, x: a + [f(a[-1], x)], xs[1:], [xs[0]])
这篇关于itertools.accumulate()与functools.reduce()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!