reduce() 有什么问题? [英] What is the problem with reduce()?

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

问题描述

网上似乎有很多关于python 3.0中reduce()函数的变化以及应该如何删除它的激烈讨论.我有点难以理解为什么会这样;我发现在各种情况下使用它是非常合理的.如果只是主观上的鄙视,我想不到这么多人会在意.

There seems to be a lot of heated discussion on the net about the changes to the reduce() function in python 3.0 and how it should be removed. I am having a little difficulty understanding why this is the case; I find it quite reasonable to use it in a variety of cases. If the contempt was simply subjective, I cannot imagine that such a large number of people would care about it.

我错过了什么?reduce() 有什么问题?

What am I missing? What is the problem with reduce()?

推荐答案

正如 Guido 在他的 Python 3000 中的 reduce() 的命运 帖子:

As Guido says in his The fate of reduce() in Python 3000 post:

所以现在reduce().这实际上是我一直最讨厌的一个,因为除了几个涉及 + 或 * 的例子,几乎每次我看到带有非平凡函数参数的 reduce() 调用时,我都需要拿起笔和纸在我理解 reduce() 应该做什么之前,绘制出实际输入该函数的内容.所以在我看来,reduce() 的适用性几乎仅限于关联运算符,在所有其他情况下,最好明确写出累加循环.

So now reduce(). This is actually the one I've always hated most, because, apart from a few examples involving + or *, almost every time I see a reduce() call with a non-trivial function argument, I need to grab pen and paper to diagram what's actually being fed into that function before I understand what the reduce() is supposed to do. So in my mind, the applicability of reduce() is pretty much limited to associative operators, and in all other cases it's better to write out the accumulation loop explicitly.

Functional Programming 中有一个很好的例子,说明了令人困惑的 reduceHOWTO 文章:

There is an excellent example of a confusing reduce in the Functional Programming HOWTO article:

快,下面的代码在做什么?

Quick, what's the following code doing?

total = reduce(lambda a, b: (0, a[1] + b[1]), items)[1]

你可以算出来,但需要时间来解开表达式来算出这是怎么回事.使用简短的嵌套 def 语句会使事情变得更好:

You can figure it out, but it takes time to disentangle the expression to figure out what's going on. Using a short nested def statements makes things a little bit better:

def combine (a, b):
    return 0, a[1] + b[1]

total = reduce(combine, items)[1]

但是如果我只是使用一个 for 循环就最好了:

But it would be best of all if I had simply used a for loop:

total = 0
for a, b in items:
    total += b

或者内置的 sum() 和一个生成器表达式:

Or the sum() built-in and a generator expression:

total = sum(b for a,b in items)

当写成 for 循环时,reduce() 的许多用途会更清晰.

Many uses of reduce() are clearer when written as for loops.

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

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