python - 有没有办法在 Python 中指定 reduce() 累加器?

标签 python haskell reduce

最近我学习了很多 Haskell,并想尝试一些它在 Python 中的巧妙技巧。据我了解,Python的reduce会自动将函数中的迭代变量和累加器设置为reduce中给出的列表的前两个值。在 Haskell 中,当我使用它的等价物 fold 时,我可以指定我想要的累加器是什么。有没有办法用 Python 的 reduce 做到这一点?

最佳答案

报价 reduce docs ,一个接口(interface)是:

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.



因此,使用初始化程序的(学术)示例可能是:
seq = ['s1', 's22', 's333']
len_sum_count = reduce(lambda accumulator, s: accumulator + len(s), seq, 0)
assert len_sum_count == 9

关于python - 有没有办法在 Python 中指定 reduce() 累加器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34161269/

相关文章:

hadoop - 将为 Hive 中的分区表创建多少个映射器和缩减器

javascript - MongoDB javascript 传递参数

python - 为什么我的神经网络成本不断增加?

haskell - 为什么 ghc 警告 ^2 需要 "defaulting the constraint to type ' Integer'?

string - 在两个子字符串之间查找字符串

带状态的 Haskell 递归数据类型

haskell - 使用Haskell monad“do”表示法定义语法树

python - 电子邮件和 map 减少作业

python - 在 Jupyter Notebook 中使用 watson_developer_cloud 时出现错误

python - Google Colab 无法更改 Python 版本