Use of the reduce function in Python

Source: Internet
Author: User

The reduce () function is also a high-order function built into Python.

The reduce () function receives a parameter similar to map (), a function f, a list, but behaves differently from map (), and reduce () the incoming function f must receive two parameters, and reduce () calls function f repeatedly on each element of the list, and returns the final result value.

For example, write an F function that receives x and Y, and returns the and of X and Y:

def f(x, y):      return + y

When you call reduce (f, [1, 3, 5, 7, 9]) , the Reduce function calculates the following:

先计算头两个元素:f( 1 3 ),结果为 4 再把结果和第 3 个元素计算:f( 4 5 ),结果为 9 再把结果和第 4 个元素计算:f( 9 7 ),结果为 16 再把结果和第 5 个元素计算:f( 16 9 ),结果为 25 由于没有更多的元素了,计算结束,返回结果 25

The above calculation is actually a summation of all the elements of the list. Although Python has built-in sum function sum (), it is simple to sum with reduce ().

reduce () can also receive a 3rd optional parameter as the initial value of the calculation. If you set the initial value to 100, the calculation:

reduce (f, [ 1 3 5 7 9 ],  100 )

The result will change to 125 because the first round calculation is:

Computes the initial value and the first element:F (1), the result is 101.

After Python 3.0.0.0, reduce is no longer in the built-in function, and it has to be from functools import reduce.

Use:

Use of the reduce function in Python

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.