1. 利用map
和reduce
编写一个str2float
函数,把字符串‘123.456‘
转换成浮点数123.456
:
from functools import reduce def str2num(s): return {‘0‘: 0, ‘1‘: 1, ‘2‘: 2, ‘3‘: 3, ‘4‘: 4, ‘5‘: 5, ‘6‘: 6, ‘7‘: 7, ‘8‘: 8, ‘9‘: 9}[s] def str2float(s): if ‘.‘ in s: # 将字符串s拆分成list类型 s = s.split(‘.‘) # 通过小数点分割,分别计算然后相加 return reduce(lambda x, y: x*10+y, map(str2num,s[0])) + reduce(lambda x, y: x/10+y, map(str2num, s[1][::-1]))/10 else: return reduce(lambda x, y: x*10+y, map(str2num, s)) s1 = str2float(‘123.456‘) print(s1)
2. 编写一个函数,可以接受一个list并利用reduce()求积:
def prod(L): def num(x, y): return x*y return reduce(num, L) L = [1,2,3,4] print(prod(L))
时间: 2024-10-14 06:48:46