Understand python reduce function, pythonreduce

Source: Internet
Author: User

Understand python reduce function, pythonreduce

Author: Panda Fang

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

Original article, reposted, please indicate the author and source, and cannot be used for commercial profit-making activities without permission

The reduce () function is a built-in function in python 2 and has been moved from python 3 to the functools module.

This is the official document.

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
Sequence is empty.

From left to right, a function with two parameters is applied to the items of a sequence cumulatively to merge 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 the initial parameter is provided, it is placed before all items in the sequence During computation. If the sequence is empty, it is the default result value for calculation.

Well, this document is hard to understand. I still don't understand it. The sequence is actually the tuple list dictionary string and other iteratable objects in python. Other programming languages may have arrays.

Reduce has three parameters.

Function A function with two parameters, required.
Sequence Tuple, list, dictionary, string, and other iteratable objects. Required Parameter
Initial Initial Value. Optional.

The reduce operation process is: In the iterative sequence (tuple, list, dictionary, string, and other iteratable objects) process, first pass the first two elements to the function parameters. After the function is processed, then, pass the obtained result and the third element as two parameters to the function parameters. The processed result and the fourth element are used as two parameters to the function parameters, and so on. If the initial value is passed in, the first element is not the first and second elements of sequence, but the initial value and the first element. After such a cumulative calculation, merge the sequence to a single return value.

 

Reduce code example, use REPL to demonstrate

>>> def add(x, y):...     return x+y...>>> from functools import reduce>>> reduce(add, [1,2,3,4])10>>>
The preceding reduce code is equivalent to 1 + 2 + 3 + 4 = 10. If you change the plus sign to the multiplication sign, it will become a factorial. Of course, it is only a summation, and there is a simpler method, as shown below:
>>> sum([1,2,3,4])10>>>

 

Many tutorials only talk about the sum of addition, which is too easy to understand. The following is a more in-depth example.


You can also splice an integer list into an integer as follows:

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

 

Use reduce for a complex sequence. Check the following code. More code will no longer use REPL, which can be written in the editor.

 1 from functools import reduce 2 scientists =({'name':'Alan Turing', 'age':105}, 3              {'name':'Dennis Ritchie', 'age':76}, 4              {'name':'John von Neumann', 'age':114}, 5              {'name':'Guido van Rossum', 'age':61}) 6 def reducer(accumulator , value): 7     sum = accumulator['age'] + value['age'] 8     return sum 9 total_age = reduce(reducer, scientists)10 print(total_age)
This code will go wrong. See the execution process.

 

 

So the code needs to be modified
 1 from functools import reduce 2 scientists =({'name':'Alan Turing', 'age':105, 'gender':'male'}, 3              {'name':'Dennis Ritchie', 'age':76, 'gender':'male'}, 4              {'name':'Ada Lovelace', 'age':202, 'gender':'female'}, 5              {'name':'Frances E. Allen', 'age':84, 'gender':'female'}) 6 def reducer(accumulator , value): 7     sum = accumulator + value['age'] 8     return sum 9 total_age = reduce(reducer, scientists, 0)10 print(total_age)
The red part of lines 7 and 9 is the modified part. You can view the document through help (reduce). reduce has three parameters. The third parameter indicates the initial value and is optional. After modification, no error occurs. The process is as follows:

 

This can still be done simply using sum.

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

Perform more advanced tasks and group by gender

from functools import reducescientists =({'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 accumulatorgrouped = reduce(group_by_gender, scientists, {'male':[], 'female':[]})print(grouped)

Output

{'male': ['Alan Turing', 'Dennis Ritchie'], 'female': ['Ada Lovelace', 'Frances E. Allen']}
We can see that the reduce Initial Value parameter is passed into a dictionary, but this may cause an error in key writing and further automation. The code for dynamically inserting a key during runtime is as follows:
grouped = reduce(group_by_gender, scientists, collections.defaultdict(list))

Of course, first import the collections Module

This can also be solved using pythonic way.

import  itertoolsscientists =({'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'})grouped = {item[0]:list(item[1])           for item in itertools.groupby(scientists, lambda x: x['gender'])}print(grouped)

 

A more obscure gameplay. If you want to work with others at work, it is not recommended that you do the same thing as the above example.

from functools import reducescientists =({'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'})grouped = reduce(lambda acc, val: {**acc, **{val['gender']: acc[val['gender']]+ [val['name']]}}, scientists, {'male':[], 'female':[]})print(grouped)

** Acc, ** {val ['gneder']... dictionary merge syntax is used here. It is introduced from python 3.5. For details, see PEP 448-Additional Unpacking Generalizations. Refer to this python-How to merge two dictionaries in a single expression? -Stack Overflow

It is recommended to write readable code in the python community. reduce is not recommended for better selection. Therefore, the built-in reduce function in python 2 is moved to the functools module.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.