reduce()的Python替代方案

2024-06-01 02:26:17 发布

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

有一个semi-famous article written by Guido himself暗示reduce()应该走渡渡鸟的路,离开语言。它甚至从Python 3(instead getting stuffed in the ^{} module)中的顶级函数降级。

与许多其他功能性编程订书钉(地图等)共同明确的选择是可用的。例如,大多数情况下,map()最好作为列表理解来编写。

我想知道的是,是否有一个类似的“更Python”的替代函数reduce。我有一点函数式编程背景(尤其是ML),所以在考虑解决方案时,我常常会想到reduce(),但如果有更好的方法来实现它们(不需要将reduce调用展开为for循环),我想知道。


Tags: 函数in语言reduceby编程articlegetting
2条回答

我想知道的是,是否有类似的“更多Python”替代reduce函数。

是和否。这取决于用例。

在相关的文章中,Guido建议大部分(但不是所有)的削减应该写成循环。在有限的情况下,他认为reduce是适用的。

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.

There aren't a whole lot of associative operators. (Those are operators X for which (a X b) X c equals a X (b X c).) I think it's just about limited to +, *, &, |, ^, and shortcut and/or.

正如Guido的链接文章所说,如果您想避免reduce(),应该只编写一个显式for循环。你可以换线

result = reduce(function, iterable, start)

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

相关问题 更多 >