map()
The function receives two parameters, one is a function, the other is a sequence, the map
incoming function functions sequentially to each element of the sequence, and returns the result as a new list.
For example, we have a function f (x) =x2, in order to function on a list, you [1, 2, 3, 4, 5, 6, 7, 8, 9]
can use the implementation of the map()
following:
def f (x): return x*xmap (f,[1,2,3,4,5,6,7,8,9]
Result
[1, 4, 9, 16, 25, 36, 49, 64, 81]
Reduce functions a function in a sequence [X1, x2, x3 ...] , the function must receive two parameters, and reduce calculates the result and the next element of the sequence, and the effect is:
reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
Practice:
Exercise 1 uses the map()
function to change the non-canonical English name entered by the user into the first capitalization, and the other lowercase canonical names. Input: [‘adam‘, ‘LISA‘, ‘barT‘]
, Output: [‘Adam‘, ‘Lisa‘, ‘Bart‘]
.
For:
def firsttoupper (x): = X[:1].upper () = x[1:].lower () = s1 + s2 return S3
Map (firsttoupper,[' AleN ', ' TOM ', ' hello ')
Explanation: X[:1]: The first character of the x string (starting from 0 to 1 subscript but not 1 subscript); X[1:]: x string of the second word selector until finally, that is, from subscript 1 to the end ...
Results:
[' Alen ', ' Tom ', ' Hello ']
Exercise 2 Python provides sum()
functions that accept a list and sum, write a prod()
function that accepts a list and takes advantage of the quadrature reduce()
.
def prod (x, y ): return x+yreduce (prod,[1,2,3,4,5,6,7,8100])
Results:
8128
Python:map () and reduce ()