# This is a learning note for the Liaoche teacher Python tutorial
1 , Map function
map () The function receives two parameters, one is the function, and the other is the ITERABLE,MAP functions the incoming function to each element of the sequence, and takes the result as a new Iterator return
# For example, there is a function f (x) =x2, to function in a list [1, 2, 3, 4, 5, 6, 7, 8, 9] on
>>> def f (x):
... return x * x
list (map (str, [1, 2, 3, 4, 5, 6, 7, 8, 9])) # because The result of the map return is iterator, so it can be computed by the list () function and returned to a list
2 , Reduce function
Reduce functions a function in a sequence [X1, x2, x3, ...] , the function must receive two parameters, and reduce accumulates the result and the next element of the sequence.
reduce (f, [X1, x2, X3, x4]) = f ( f (   Span style= "font-family: Microsoft JAS Black; background: #FF99CC" >f (x1, x2)     x3" ,       x4)
# change "13579" to 13579
From Functools import reduce
DIGITS = {' 0 ': 0, ' 1 ': 1, ' 2 ': 2, ' 3 ': 3, ' 4 ': 4, ' 5 ': 5, ' 6 ': 6, ' 7 ': 7, ' 8 ': 8 '
Method One:
def str2int (s):
DEF fn (x, y):
return x * ten + y
def char2num (s):
return Digits[s]
return reduce (FN, map (Char2num, s)) # map (Char2num, s) Convert a string to a single int
Method Two:
def char2num (s):
return Digits[s]
def str2int (s):
return reduce (lambda x, y:x * + y, map (Char2num, s))
X, y: parameters that need to be passed in
X * + y: Formula
Map (Char2num, s): List group, source of parameters
Reduce: Cumulative calculation
2 , examples
1 , using the map () function, List becomes the first letter uppercase, the other lowercase specification.
Input: [' Adam ', ' Lisa ', ' Bart '], output: [' Adam ', ' Lisa ', ' Bart ']:
#-*-Coding:utf-8-*-
def normalize (name):
return str.capitalize(name) # str_capitailize (), will C7>str Convert first letter uppercase remaining lowercase
L1 = [' Adam ', ' LISA ', ' BarT ']
L2 = List (map (normalize, L1))
Print (L2)
2 , the sum () function provided by Python can accept a list and sum, write a prod () function that accepts a list and uses the reduce () to calculate the product:
#-*-Coding:utf-8-*-
From Functools import reduce
def prod (L):
return reduce (lambda x,y:x*y,l)
Print (' 3 * 5 * 7 * 9 = ', prod ([3, 5, 7, 9]))
3 , use map and reduce to write a str2float function, convert the string ' 123.456 ' into a floating-point number 123.456:
#-*-Coding:utf-8-*-
From Functools import reduce
def str2float (s):
digest={' 1 ': 1, ' 2 ': 2, ' 3 ': 3, ' 4 ': 4, ' 5 ': 5, ' 6 ': 6} # definition Str corresponding to the int
gt,lt= s.split ('. ') # cut characters,s.split ('. ') , to . as a separator
Length=len (LT)
def char2sum (x):
return Digest[x]
Gt=reduce (Lambda X,y:x*10+y,map (CHAR2SUM,GT))
Lt=reduce (Lambda X,y:x*10+y,map (CHAR2SUM,LT))
lt=lt/ POW (10,length) # POW ( x, y) , calculates the x - Square
Return GT+LT
Python Learning note __4.1.1 map/reduce