Skip to content

Commit 72b836d

Browse files
authored
练习函数式编程的map和reduce
1 parent f11ad6f commit 72b836d

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

test8.py

+76
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
# 练习函数式编程的map和reduce
2+
from functools import reduce
3+
4+
5+
l = [x for x in range(-10, 10, 2)]
6+
print(l)
7+
l = list(map(abs, l))
8+
print(l)
9+
10+
11+
# reduce是将列表做累计运算
12+
# lambda是匿名函数
13+
num = reduce(lambda x, y: x + y, l)
14+
print(num)
15+
16+
17+
# 将一个字符串转换成整型
18+
def str2int(s):
19+
def char2int(ch):
20+
c = {str(x): x for x in range(10)}
21+
return c[ch]
22+
23+
def fun(n1, n2):
24+
return n1*10 + n2
25+
26+
return reduce(fun, map(char2int, s))
27+
28+
29+
num = str2int('12345')
30+
print(type(num), num)
31+
32+
33+
# 这是使用匿名函数的简便版
34+
def str2int2(s):
35+
ch = {str(x): x for x in range(10)}
36+
return reduce(lambda x, y: x*10+y, map(lambda x: ch[x], s))
37+
38+
39+
num = str2int2('12345')
40+
print(type(num), num)
41+
42+
43+
# 作业:利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字
44+
def normalize(name):
45+
# capitalize()函数是将字符串的首字母大写
46+
return list(map(lambda x: x.capitalize(), name))
47+
48+
49+
L = ['adam', 'LISA', 'barT']
50+
print(normalize(L))
51+
52+
53+
# 作业2:Python提供的sum()函数可以接受一个list并求和,请编写一个prod()函数,可以接受一个list并利用reduce()求积
54+
def prod(x, y):
55+
return x*y
56+
57+
58+
num = reduce(prod, [3, 5, 7, 9])
59+
print(num)
60+
61+
62+
# 作业3:利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456
63+
def str2float(s):
64+
ch = {str(x): x for x in range(10)}
65+
# 先将字符串分割
66+
L = s.split('.')
67+
# 整数部分
68+
n1 = reduce(lambda x, y: x*10 + y, map(lambda x: ch[x], L[0]))
69+
# 小数部分
70+
n2 = reduce(lambda x, y: x * 10 + y, map(lambda x: ch[x], L[1]))
71+
n2 *= 0.1**len(L[1])
72+
return n1+n2
73+
74+
75+
num = str2float('123.456')
76+
print(num)

0 commit comments

Comments
 (0)