0%

廖雪峰Python教程练习题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# names.py
def normalize(name):
return name.capitalize()

L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)
# 求积
from functools import reduce
def prod(L):
def prod1(x, y):
return x * y
return reduce(prod1, L)


print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
# 转换字符串
'''
先记住这个结果,等会实现需要用到
a = '123.456'
n = a.index('.')
b = [x for x in a[:n]]
print(b)
结果:
['1', '2', '3']
'''
def str2float(s):
def fn(x, y):
return x * 10 + y
n = s.index('.')
s1 = list(map(int, [x for x in s[:n]]))
s2 = list(map(int, [y for y in s[n+1: ]]))
return reduce(fn,s1) + (reduce(fn, s2) / 10 ** len(s2))

print(str2float('123.456'))
"""
输出结果:

['Adam', 'Lisa', 'Bart']
3 * 5 * 7 * 9 = 945
123.456

"""