带三个参数的reduce函数 [英] Reduce function with three parameters

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

问题描述

reduce 函数如何在 python3 中使用三个参数而不是两个参数工作.所以,对于两个,

How does reduce function work in python3 with three parameters instead of two. So, for two,

tup = (1,2,3)
reduce(lambda x, y: x+y, tup)

我得到了这个.这只会总结 tup 中的所有元素.但是,如果你给reduce函数三个像下面这样的参数,

I get this one. This would just sum up all the elements in tup. However, if you give reduce function three parameters like this below,

tup = (1,2,3)
reduce(lambda x, y: x+y, tup, 6)

这将为您提供 12 的值.我查看了 python3 的文档,它说第三个参数是一个初始值设定项.也就是说,如果没有插入第三个参数,那么默认的初始化器是什么?

this would give you a value of 12. I checked up on the documentation for python3 and it says the third argument is an initializer. That said, then what is the default initializer if the third argument is not inserted?

推荐答案

如果省略第三个参数,则使用 tup 中的 first 值作为初始值设定项.

If you omit the third parameter, then the first value from tup is used as the initializer.

或者,换句话说,reduce() 将可选的第三个参数放在第二个参数的值之前(如果存在).

Or, to put it a different way, reduce() places the optional 3rd parameter before the values of the second argument, if present.

此外,这意味着如果第二个参数是一个 序列,则第三个参数作为默认值,就像第二个参数只有 一个 元素(和没有明确的初始化参数),将是默认返回值.

Moreover, that means that if the second argument is an empty sequence, that third argument serves as the default, just as a second argument with only one element (and no explicit initializer argument), would be the default return value.

functools.reduce() 文档 包含函数的 Python 版本:

The functools.reduce() documentation includes a Python version of the function:

def reduce(function, iterable, initializer=None):
    it = iter(iterable)
    if initializer is None:
        value = next(it)
    else:
        value = initializer
    for element in it:
        value = function(value, element)
    return value

注意 initializer 如何在不是 None 时用作第一个值,而不是 iterable 中的第一个值.

Note how the initializer, when not None, is used as the first value instead of a first value from iterable.

这篇关于带三个参数的reduce函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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