Format:
Map (function, list)
Reduce (function, list)
Difference:
1.map for each element of the list, returning a new list
2.reduce consolidates each element of the list, returning a new value
Advantage:
1.map, reduce comes with a for loop, reducing the amount of code
First, the use of map
#!/usr/bin/python
def f (x):
Return x*x
Lis = [1, 2, 3, 4, 5]
Map_list =map (f, Lis) operation in #将lis的元素分别在f () function
Print Lis
Print Map_list
#str
Map_list1 = map (str, LIS); #将lis的元素分别在str函数中转换成char类型
Print Lis
Print Map_list1
Second, the use of reduce
def fsum (x, y):
return x+y;
Lis = [1, 3, 5, 7]
Lis1 = reduce (fsum, LIS)
Print Lis1
Third, map \ Reduce mixed use
def fsum (x, y):
return x+y;
Lis = [1, 3, 5, 7]
Lis1 = reduce (fsum, LIS)
Print Lis1
#获取数字和
def fadd (x, y):
Return X*10+y
num = reduce (fadd, LIS);
print ' Get num: ', num
Stri = str (num);
print ' Num2str: ', stri;
#将str转数字
def ch2num (s):
return {' 0 ': 0, ' 1 ': 1, ' 2 ': 2, ' 3 ': 3, ' 4 ': 4, ' 5 ': 5, ' 6 ': 6, ' 7 ': 7, ' 8 ': 9}[s] #此函数执行返回过程如下:
# {' 0 ': 0, ' 1 ': 1, ' 2 ': 2, ' 3 ': 3, ' 4 ': 4, ' 5 ': 5, ' 6 ': 6, ' 7 ': 7, ' 8 ': 9}[stri[0]]--->return 8
# {' 0 ': 0, ' 1 ': 1, ' 2 ': 2, ' 3 ': 3, ' 4 ': 4, ' 5 ': 5, ' 6 ': 6, ' 7 ': 7, ' 8 ': 9}[stri[1]]--->return 8
# {' 0 ': 0, ' 1 ': 1, ' 2 ': 2, ' 3 ': 3, ' 4 ': 4, ' 5 ': 5, ' 6 ': 6, ' 7 ': 7, ' 8 ': 9}[stri[2]]--->return 8
# {' 0 ': 0, ' 1 ': 1, ' 2 ': 2, ' 3 ': 3, ' 4 ': 4, ' 5 ': 5, ' 6 ': 6, ' 7 ': 7, ' 8 ': 9}[stri[4]]--->return 8
lis= map (Ch2num, stri);
print ' Str2Num: ', Lis;
#将数字列表lis整合
def f (x, Y):
return x*10+y;
num = reduce (f, strin);
print ' Add: ', num;
Iv. Record of difficulties
Temporarily unable to solve, first record, stay in depth and then look back
Organized into aStr2Int
The function is:
def str2int (s):
DEF fn (x, y):
return x * ten + y
def char2num (s):
return {' 0 ': 0, ' 1 ': 1, ' 2 ': 2, ' 3 ': 3, ' 4 ': 4, ' 5 ': 5, ' 6 ': 6, ' 7 ': 7, ' 8 ': 9}[s]
Return reduce (FN, map (Char2num, s))
Lis = [' 1 ', ' 2 ', ' 3 ']
num = Str2Int (LIS)
Print num;
run Result: 123
can also be further simplified with a lambda function:
def char2num (s):
return {' 0 ': 0, ' 1 ': 1, ' 2 ': 2, ' 3 ': 3, ' 4 ': 4, ' 5 ': 5, ' 6 ': 6, ' 7 ': 7, ' 8 ': 9}[s]
def str2int (s):
return reduce (lambda x,y:x*10+y, map (Char2num, s))
Lis = [' 1 ', ' 2 ', ' 4 ']
num = Str2Int (LIS)
Print num;
Operation Result: 124
Python high-order functions: Map, reduce