实现说明
顶层就这几处状态:daily。
使用要点
- 跑完文件,输出里会留下标记——
running total:、paired:、running product:。
常见问题
除了语言工具链还要下载什么吗?
除了这个语言的工具链,什么都不用再下载。 全部导入都来自标准库:itertools、operator。 文件用顶层绑定保存自己的状态:daily。
代码示例
from itertools import accumulate, islice
from operator import mul
daily = [120, 340, 0, 90, 210]
print("running total:", list(accumulate(daily)))
# zip lines up the daily contribution with the running total to show how each step enters the sum
print("paired:", list(zip(daily, accumulate(daily))))
# any binary function: a running product multiplies item by item
print("running product:", list(accumulate([2, 3, 4], mul)))
# rolling maximum: initial provides the starting point for comparisons
print("running max:", list(accumulate([3, 1, 4, 1, 5], max, initial=0)))
# lazy evaluation: accumulate returns an iterator, and islice takes only the prefix you need
print("first three:", list(islice(accumulate(daily), 3)))