最近我学习了很多 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/