Python 相当于 clojure 减少

Stu*_*art 5 python

在Clojure中,我们有一个这样的函数

(reductions str ["foo" "bar" "quax"])
=> ["foo" "foobar" "foobarquax"]

Run Code Online (Sandbox Code Playgroud)

或者

(reductions + [1 2 3 4 5])
=> [1 3 6 10 15]
Run Code Online (Sandbox Code Playgroud)

它基本上只是减少但它收集中间结果。

我在 Python 中找不到等价物。是否存在基本库函数。

蟒蛇 3

And*_*ely 6

您可以使用 itertools.accumulate

from itertools import accumulate

l = [1, 2, 3, 4, 5]

print([*accumulate(l)])
Run Code Online (Sandbox Code Playgroud)

印刷:

[1, 3, 6, 10, 15]
Run Code Online (Sandbox Code Playgroud)