您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Python中相当于Haskell scanl

在Python中相当于Haskell scanl

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

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
python 2022/1/1 18:44:33 有315人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶