python任意累积_pythonic减少与累加和任意lambda函数?

What would be the Pythonic way of performing a reduce with accumulation?

For example, take R's Reduce(). Given a list and an arbitrary lambda function it allows for yielding a vector of accumulated results instead of only the final result by setting accumulate=T. An example for this with a simple multiplication as lambda function would be (taken from this answer):

Reduce(`*`, x=list(5,4,3,2), accumulate=TRUE)

# [1] 5 20 60 120

It is important that an arbitrary lambda function (like lambda x, y: ...) can be used, so solutions that allow for e.g. only using a sum, multiplication, or else won't do the trick. I was not able to come up with a Pythonic solution to do this with e.g. Python's itertools or functools, but there might be a way. And though there are numerous other questions and answers on reduce and specially accumulation with Python I did not spot a generic answer so far.

A non-Pythonic example using a loop for performing a accumulated reduce with an arbitrary lambda function could look like this:

# the source list

l = [0.5, 0.9, 0.8, 0.1, 0.1, 0.9]

# the lambda function for aggregation can be arbitrary

# this one is just made up for the example

func = lambda x, y: x * 0.65 + y * 0.35

# the accumulated reduce:

# a) the target list with initializer value hardcoded

l2 = [l[0]]

# b) the loop

for i in range(1, len(l)):

l2 += [func(

l2[i-1], # last value in l2

l[i] # new value from l

)]

So: how would you do a reduce with accumulation and arbitrary lambda function in a Pythonic way?

解决方案

In Python 3 (introduced in 3.2, ability to pass the function added in 3.3) this is already implemented, in itertools.accumulate. Just use it like this:

from itertools import accumulate

list(accumulate([5, 4, 3, 2], lambda a, b: a*b))

# [5, 20, 60, 120]

If you are using an earlier Python version, or want to implement it yourself, and you really want any arbitrary lambda (that takes two arguments) to work, then you could use the generator which is given in the documentation of the above:

def accumulate(iterable, func=operator.add):

'Return running totals'

# accumulate([1,2,3,4,5]) --> 1 3 6 10 15

# accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120

it = iter(iterable)

try:

total = next(it)

except StopIteration:

return

yield total

for element in it:

total = func(total, element)

yield total

The usage is exactly the same as above.

If you are using numpy, then there exists a faster solution, at least for all numpy.ufuncs. These include basically the same functions that the standard library module math provides, and then some. You can find a complete list here.

Every numpy.ufunc has the accumulate method, so you can just do:

import numpy as np

np.multiply.accumulate([5, 4, 3, 2])

# array([ 5, 20, 60, 120])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值