Python替代reduce() [英] Python alternative to reduce()

查看:335
本文介绍了Python替代reduce()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Guido自己撰写的半文章暗示那么 reduce()应该成为dodo的方式并离开语言。它甚至从Python 3中的顶级函数降级(改为填充 functools 模块)。

通过许多其他功能性编程主要代码(地图等)可用。例如,大多数情况下, map()最好写成列表理解。



d想知道的是,是否存在类似于减少函数的更pythonic替代方案。我有一些函数式编程背景(特别是ML),所以当考虑解决方案时,我经常想到 reduce(),但是如果有更好的方法做他们(短的展开减少调用到一个for循环)我想知道。

解决方案

作为Guido的链接文章说,如果你想避免 reduce(),你应该写一个明确的for循环。您可以替换该行

  result = reduce(function,iterable,start)



by

 结果=开始
for x in iterable:
result = function(result,x)


There is a semi-famous article written by Guido himself hinting that reduce() should go the way of the dodo and leave the language. It was even demoted from being a top-level function in Python 3 (instead getting stuffed in the functools module).

With many other functional programming staples (map, etc) common clear alternatives are available. For example, most of the time a map() is better written as a list comprehension.

What I'd like to know is if there is a similar "more pythonic" alternative to the reduce function. I have a bit of a functional programming background (ML in particular), so reduce() often springs to my mind when thinking of a solution, but if there's a better way to do them (short of unrolling a reduce call into a for loop) I'd like to know.

解决方案

As Guido's linked article says, you should just write an explicit for loop if you want to avoid reduce(). You can replace the line

result = reduce(function, iterable, start)

by

result = start
for x in iterable:
    result = function(result, x)

这篇关于Python替代reduce()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆