Python's reduce question

reduce explains: reduce acts a function on a sequence [x1, x2, x3,.] This function must take two arguments. Reduce accumulates the result and the next element of the sequence.
Code:

>>> from functools import reduce
>>> def add(x, y):
...     return x + y
...
>>> reduce(add, [1, 2,3])-sharp6
>>> reduce(add, [1])-sharp1

question: two parameters are required, parameter x and parameter y are what, reduce (add, [1]). In this case, I don"t understand how this reduce works

Mar.22,2021

reduce is roughly equivalent to:

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

as far as your add is concerned, it can be understood this way.

reduce(add,[1,2,3]) = add(add(1,2),3)

add must accept two parameters, there is reduce (add,l) for sequence l, see the sentence "the result continues to accumulate with the next element of the sequence", the first result is add (l [0], the next element of l [1]), l is l [2], so the next step is add (add (l [0], l [1]), l [2]), it should be understood that XQuery y is the element of the sequence.
and reduce (add, [1]), look at the code. When the first element is taken out, value=1,it is empty, so the final value of return is 1

.

I have seen an explanation of this in "Think Python", which has been compiled into an article. You can refer to
python-sum-map-filter-reduce/" rel=" nofollow noreferrer "> http://yarving.historytale.co.

.
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1bf7471-313c1.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1bf7471-313c1.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?