Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

python - Reduce function with three parameters

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...