Reduce function with three parameters

前端 未结 3 1156
谎友^
谎友^ 2020-12-10 01:51

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)
<         


        
3条回答
  •  时光说笑
    2020-12-10 02:07

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

    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.

    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
    

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

提交回复
热议问题