在python中等效的Haskell scanl

时间:2013-01-20 10:58:47

标签: python haskell functional-programming

我想知道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]

谢谢:)

4 个答案:

答案 0 :(得分:15)

你可以使用它,如果它更优雅:

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)。它的实现如下。实施可能会给你一些想法:

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

答案 1 :(得分:1)

我有类似的需求。这个版本使用python list comprehension

def scanl(data):
    '''
    returns list of successive reduced values from the list (see haskell foldl)
    '''
    return [0] + [sum(data[:(k+1)]) for (k,v) in enumerate(data)]


>>> scanl(range(1,11))

给出:

[0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55]

答案 2 :(得分:1)

Python 3.8开始,并引入assignment expressions (PEP 572):=运算符),它可以命名表达式的结果,我们可以使用列表推导来复制< em>向左扫描操作:

acc = 0
scanned = [acc := acc + x for x in [1, 2, 3, 4, 5]]
# scanned = [1, 3, 6, 10, 15]

或者以一种通用的方式,给出一个列表,一个归约函数和一个初始化的累加器:

items = [1, 2, 3, 4, 5]
f = lambda acc, x: acc + x
accumulator = 0

我们可以从左侧扫描items并用f缩小它们:

scanned = [accumulator := f(accumulator, x) for x in items]
# scanned = [1, 3, 6, 10, 15]

答案 3 :(得分:0)

像往常一样,Python生态系统也充满了解决方案:

Toolz有一个累积,能够将用户提供的函数作为参数。我用lambda表达式测试了它。

https://github.com/pytoolz/toolz/blob/master/toolz/itertoolz.py

https://pypi.python.org/pypi/toolz

和more_itertools一样

http://more-itertools.readthedocs.io/en/stable/api.html

我没有从more-itertools测试版本,但它也可以使用用户提供的功能。

相关问题