问题描述
我想知道 python 中是否有一个内置函数用于等效的 Haskell scanl
,因为 reduce
相当于 foldl
>.
I would like to know if there is a built in function in python for the equivalent Haskell scanl
, as reduce
is the equivalent of foldl
.
这样做的东西:
Prelude> scanl (+) 0 [1 ..10]
[0,1,3,6,10,15,21,28,36,45,55]
问题不在于如何实现它,我已经有 2 个实现,如下所示(但是,如果您有更优雅的实现,请随时在此处展示).
The question is not about how to implement it, I already have 2 implementations, shown below (however, if you have a more elegant one please feel free to show it here).
第一个实现:
# Inefficient, uses reduce multiple times
def scanl(f, base, l):
ls = [l[0:i] for i in range(1, len(l) + 1)]
return [base] + [reduce(f, x, base) for x in ls]
print scanl(operator.add, 0, range(1, 11))
给出:
[0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55]
第二次实施:
# Efficient, using an accumulator
def scanl2(f, base, l):
res = [base]
acc = base
for x in l:
acc = f(acc, x)
res += [acc]
return res
print scanl2(operator.add, 0, range(1, 11))
给出:
[0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55]
谢谢:)
推荐答案
你可以使用这个,如果它更优雅:
You can use this, if its more elegant:
def scanl(f, base, l):
for x in l:
base = f(base, x)
yield base
像这样使用:
import operator
list(scanl(operator.add, 0, range(1,11)))
Python 3.x 具有 itertools.accumulate(iterable,func= operator.add)
.它的实现如下.实施可能会给你一些想法:
Python 3.x has itertools.accumulate(iterable, func= operator.add)
. It is implemented as below. The implementation might give you ideas:
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)
total = next(it)
yield total
for element in it:
total = func(total, element)
yield total
这篇关于相当于python中的Haskell scanl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!