Reduce function with three parameters

限于喜欢 提交于 2019-12-03 18:01:14

问题


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)

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)

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?


回答1:


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.




回答2:


Providing a tuple as a third parametr we will be able to calculate and return from reduce multiple values.

from functools import reduce
def mean(my_list):                  # == sum(my_list) / len(my_list)
    return (lambda x: x[0]/x[1]) (reduce(lambda x, y : (x[0]+y, x[1]+1), 
                                                my_list, (0, 0,)))



回答3:


reduce optional third argument :

>>> import functools
>>> test = []
>>> functools.reduce((lambda x,y: x+y), test, "testing")


来源:https://stackoverflow.com/questions/19589233/reduce-function-with-three-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!