Python functools. reduce usage, functools. reduce

Source: Internet
Author: User

Python functools. reduce usage, functools. reduce

After python 3.0, reduce is no longer in the built-in function. to use it, you need to import reduce from functools.

Reduce usage

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.

 

This means that the function is used continuously for sequence. If initial is not given, two elements of sequence will be transferred for the first call, and the result of the previous call and the next element of sequence will be passed to the function. if initial is given, the first element of initial and sequence is passed to the function for the first time.

From functools import reduce (lambda x, y: x + y, [1, 2, 3]) Outputs 6 reduce (lambda x, y: x + y, [1, 2, 3], 9) Output 15 reduce (lambda x, y: x + y, [1, 2, 3], 7) Output 13

  

* The standard functool Library also provides many functions. For more information, see the online documentation.

Related Article

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.