itertools.accumulate()与functools.reduce() [英] itertools.accumulate() versus functools.reduce()

查看:150
本文介绍了itertools.accumulate()与functools.reduce()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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:

  1. accumulate()默认为求和,但不允许您显式提供额外的初始条件,而reduce()没有默认为任何方法,但允许您提供用于1/0元素序列的初始条件,和
  2. accumulate()首先采用可迭代,而reduce()首先采用该函数.
  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
  2. accumulate() takes the iterable first while reduce() 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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆