Map and reduce functions in Python

Source: Internet
Author: User

① in terms of parameters:

Map () Function:

Map () contains two parameters, the first one is a function, the second is a sequence (list or tuple). where a function (that is, a function of the first parameter position of a map) can receive one or more parameters .

Reduce () function:

The first parameter of reduce () is a function, and the second is a sequence (list or tuple). However, its function must receive two parameters .

② from the numerical effect on the transfer in terms of:

Map () is the function of passing the incoming functions to each element of the sequence sequentially, each of which is "acting" on its own by the function; (see chestnuts below)

Reduce () is the function of the descendant to the first element of the sequence to get the result, the result will continue to work with the next element (cumulative calculation),

The end result is the interaction of all elements. (See chestnuts below)

Give me a chestnut:

Map () Function:

[Python]View plain copy
  1. # Pass in a parameter
  2. def one_p (x):
  3. return x * x
  4. Print ' map1.1: ', Map (one_p, Range (1, 5))
  5. #结果: map1.1: [1, 4, 9, 16]
  6. Print ' map1.2: ', Map (one_p, [1, 2, 3, 4, 5, 6])
  7. #结果: map1.2: [1, 4, 9, 16, 25, 36]
  8. # Incoming multiple parameters
  9. A = [1, 2, 3, 4, 5]
  10. b = [1, 1, 6, 2, 3]
  11. c = [1, 2, 3, 4, 5]
  12. s = map (lambda (x, Y, z): x * y * z, zip (A, B, c))
  13. Print ' map2: ', S
  14. #结果: map2: [1, 4, 54, 32, 75]


Reduce () function:

[Python]View plain copy
  1. R1 = reduce (lambda x, y:x * y, (2, 2, 6, 2)) #运算过程: (((2*2) *6)
  2. r2 = reduce (lambda x, y:x * y, (2, 2, 6), 2) #<span > Operation process: ((2*2) *6) </span>
  3. Print ' R1: ', R1 # Result: r1:48
  4. Print ' R2: ', R2 # Result: r2:48

Map and reduce functions 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.