简体   繁体   English

itertools.accumulate()与functools.reduce()

[英]itertools.accumulate() versus 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; 在Python 3.3中, itertools.accumulate()通常会重复对提供的iterable应用加法运算,现在可以将函数参数作为参数; this means it now overlaps with functools.reduce() . 这意味着它现在与functools.reduce()重叠。 With a cursory look, the main differences between the two now would seem to be: 粗略看一下,现在两者之间的主要区别似乎是:

  1. accumulate() defaults to summing but doesn't let you supply an extra initial condition explicitly while reduce() doesn't default to any method but does let you supply an initial condition for use with 1/0-element sequences, and accumulate()默认为求和但不允许显式提供额外的初始条件,而reduce()不默认为任何方法,但允许您提供初始条件以用于1/0元素序列,并且
  2. accumulate() takes the iterable first while reduce() takes the function first. accumulate()首先获取iterable,而reduce()首先获取该函数。

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? 或者这仅仅是两个函数的行为问题,最初的不同用途开始随时间收敛?

It seems that accumulate keeps the previous results, whereas reduce (which is known as fold in other languages) does not necessarily. 似乎accumulate保留了先前的结果,而reduce (在其他语言中称为折叠)并不一定。

eg list(accumulate([1,2,3], operator.add)) would return [1,3,6] whereas a plain fold would return 6 例如list(accumulate([1,2,3], operator.add))将返回[1,3,6]而普通折叠将返回6

Also (just for fun, don't do this) you can define accumulate in terms of reduce 另外(只是为了好玩,不要这样做)你可以用reduce来定义accumulate

def accumulate(xs, f):
    return reduce(lambda a, x: a + [f(a[-1], x)], xs[1:], [xs[0]]) 

You can see in the documentation what the difference is. 您可以在文档中看到有什么区别。 reduce returns a single result, the sum, product, etc., of the sequence. reduce返回单个结果,序列的总和,产品等。 accumulate returns an iterator over all the intermediate results. accumulate所有中间结果上返回一个迭代器。 Basically, accumulate returns an iterator over the results of each step of the reduce operation. 基本上, accumulatereduce操作的每个步骤的结果上返回一个迭代器。

itertools.accumulate is like reduce but returns a generator* instead of a value. itertools.accumulatereduce类似,但返回生成器*而不是值。 This generator can give you all the intermediate step values. 该生成器可以为您提供所有中间步骤值。 So basically reduce gives you the last element of what accumulate will give you. 所以基本上减少会给你积累的最后一个元素。

*A generator is like an iterator but can be iterated over only once. *生成器就像一个迭代器,但只能迭代一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM