itertools.accumulate() versus functools.reduce()

前端 未结 3 1443
礼貌的吻别
礼貌的吻别 2021-02-02 10:40

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 me

3条回答
  •  离开以前
    2021-02-02 11:04

    It seems that accumulate keeps the previous results, whereas reduce (which is known as fold in other languages) does not necessarily.

    e.g. list(accumulate([1,2,3], operator.add)) would return [1,3,6] whereas a plain fold would return 6

    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]]) 
    

提交回复
热议问题