有没有一种方法可以在Python中指定reduce()累加器?

2024-04-19 04:16:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近学习了很多Haskell,并想尝试一下它在Python中的一些巧妙的技巧。据我所知,Python的reduce自动设置传递给reduce中列表的前两个值的迭代变量和累加器。在Haskell中,当我使用它的等价物fold时,我可以指定我想要的累加器。有没有一种方法可以用Python的reduce实现呢?在


Tags: 方法reduce列表技巧haskellfold累加器
1条回答
网友
1楼 · 发布于 2024-04-19 04:16:01

引用reduce docs,接口是:

reduce(function, iterable[, initializer])

If the optional initializer is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty. If initializer is not given and iterable contains only one item, the first item is returned.

例如,初始值设定项可以是:

^{pr2}$

相关问题 更多 >