Detailed explanation of reduce function in python

1. In python2, the reduce function is a built-in function

2. In python3, the function has been moved to the functools module

3. Official documents:

reduce(...)
reduce(function, sequence[, initial]) -> value

Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.

Merges a sequence into a single value by applying a two-argument function cumulatively to the items of a sequence from left to right.

For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5).

If the initial parameter is provided, it will be placed in front of all items in the sequence during calculation. If the sequence is empty, it will be the default result value of the calculation.

 

4. Explanation:

reduce has three parameters:

  • function: a function with two parameters, required parameters
  • sequence: iterable objects such as tuples and lists, required parameters
  • initial: initial value, optional parameters

 

5. The working process of reduce is:

In the process of iterating sequence (tuple, list, dictionary, string and other iterable objects),

  1. First, pass the first two elements to the function parameters. After the function is processed,
  2. Then pass the result and the third element as two parameters to the function parameters,
  3. The result obtained after function processing and the fourth element are passed as two parameters to the function parameters, and so on.

If the initial value is passed in, then the first and second elements of the sequence are not passed first, but the initial value and the first element.

After such cumulative calculations the sequence is merged into a single return value

 

7. Beginner 1

from functools import reduce
def add(x,y):
    return x+y

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

In fact, it is equivalent to 1 + 2 + 3 + 4 = 10. If the plus sign is changed to a multiplication sign, it becomes a factorial.

Of course, there is a simpler way if it is just a sum.

sum([1,2,3,4])
10

 

8. Elementary level 2

Concatenate a list of integers into integers:

from functools import reduce

reduce(lambda x, y: x * 10 + y, [1 , 2, 3, 4, 5])
12345

 

9. Advanced 1

from functools import reduce

scientists =({'name':'Alan Turing', 'age':105, 'gender':'male'},
             {'name':'Dennis Ritchie', 'age':76, 'gender':'male'},
             {'name':'Ada Lovelace', 'age':202, 'gender':'female'},
             {'name':'Frances E. Allen', 'age':84, 'gender':'female'})
def reducer(accumulator , value):
    sum = accumulator['age'] + value['age']
    return sum
total_age = reduce(reducer, scientists)
print(total_age)
 'int' object is not subscriptable

Error analysis:

In the first round of loop: accumulator = {'name':'Alan Turing', 'age':105}

                          value =            {'name':'Dennis Ritchie', 'age':76}

During the second round of loop: accumulator = sum = 105 + 76 = 181

                          value           =  {'name':'John von Neumann', 'age':114}

So an error is reported, as shown below:

 

 Revise:

from functools import reduce
scientists =({'name':'Alan Turing', 'age':105, 'gender':'male'},
             {'name':'Dennis Ritchie', 'age':76, 'gender':'male'},
             {'name':'Ada Lovelace', 'age':202, 'gender':'female'},
             {'name':'Frances E. Allen', 'age':84, 'gender':'female'})
def reducer(accumulator , value):
    sum = accumulator + value['age']
    return sum
total_age = reduce(reducer, scientists, 0)
print(total_age)

result:

467

analyze:

reduce has three parameters. The third parameter means the initial value and is an optional parameter.

 

After modification, there will be no errors. The process is as follows:

This can still be done more simply using sum

 

sum([x['age'] for x in scientists ])

 

10. Advanced 2

from functools import reduce
scientists =({'name':'Alan Turing', 'age':105, 'gender':'male'},
             {'name':'Dennis Ritchie', 'age':76, 'gender':'male'},
             {'name':'Ada Lovelace', 'age':202, 'gender':'female'},
             {'name':'Frances E. Allen', 'age':84, 'gender':'female'})
def group_by_gender(accumulator , value):
    accumulator[value['gender']].append(value['name'])
    return accumulator
grouped = reduce(group_by_gender, scientists, {'male':[], 'female':[]})
print(grouped)
{'male': ['Alan Turing', 'Dennis Ritchie'], 'female': ['Ada Lovelace', 'Frances E. Allen']}

 

 

reference:

https://www.cnblogs.com/lonkiss/p/understanding-python-reduce-function.html

Guess you like

Origin blog.csdn.net/bailixuance/article/details/85098215