#python函数式编程之reduce用法
reduce(f,序列)
reduce用f在序列上的相邻元素上作用,然后把结果继续和下一个元素迭代计算
reduce返回什么结果关键看f函数
- example 1: reduce计算和
1
2
3
4
5from functools import reduce
def add(x,y):
return x+y
ans = reduce(add,[1,2,3,4,5,6,7,8,9])
print(ans)
1 | 45 |
- example 2: reduce计算积的和
1
2
3
4
5from functools import reduce
def fn(x,y):
return x*10+y
ans = reduce(fn,[1,2,3,4,5,6,7,8,9])
print(ans)
1 | 123456789 |
- example 3: reduce把字符串转为数字
1
2
3
4
5
6
7def char2num(a):
digit = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}
return digit[a]
ans = reduce(fn,map(char2num,['1','2','3']))
ans1 = reduce(fn,map(char2num,'123456'))
print(ans,ans1,end=' ')
print()
1 | 123 123456 |
- example 4: 提炼为cha2num函数
1
2
3
4
5
6
7
8
9digit = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}
def str2num(s):
def fn(x,y):
return x*10+y
def char2num(a):
return digit[a]
return reduce(fn,map(char2num,s))
s = '12345678'
print(str2num(s))
1 | 12345678 |
- example5: cha2num函数用lamda函数式简化
1
2
3def str2num(s):
return reduce(lambda x,y:x*10+y,map(lambda x:digit[x],s))
print(str2num('321'))
1 | 321 |
- test1:将字符串转为首字母大写,其余小写
1
2
3
4
5
6def normalize(name):
ans = name.lower().capitalize()
return ans
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize,L1))
print(L2)
1 | ['Adam', 'Lisa', 'Bart'] |
- test2:求积
1
2
3def prod(L):
return reduce(lambda x,y:x*y,L)
print('3*5*7*9 = ',prod([3,5,7,9]))
1 | 3*5*7*9 = 945 |
- test3:字符串转为浮点数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19digit = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}
def str2float(s):
j = 0
ans1 = 0.0
ans2 = 0
length = len(s)
flag = False
for i in (range(length)):
if(s[i] == '.'):
j = 0
flag = True
continue
if(flag):
j = j + 1
ans2 = ans2+digit[s[i]]*pow(0.1,j)
else:
ans1 = ans1*10+digit[s[i]]
return ans1+ans2
print(str2float('12.23'))
1 | 12.23 |