我想知道在 python 中是否有等效 Haskell 的内置函数,scanl
就像.reduce
foldl
这样做的东西:
Prelude> scanl (+) 0 [1 ..10]
[0,1,3,6,10,15,21,28,36,45,55]
问题不在于如何实现它,我已经有 2 个实现,如下所示(但是,如果您有更优雅的实现,请随时在此处展示)。
第一次实现:
# 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]
谢谢 :)