函数式编程/高阶函数/map/reduce 函数

题目:利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字

def normalize(name):
return name.capitalize()
L1=["asd","qweY",'aSq']
L2=list(map(normalize,L1))
print(L2)


题目:Python 提供的 sun() 函数可以接受一个list并求和,请编写一个prod() 函数,可以接受一个list 并利用 reduce() 求积。


from functools import reduce
def prod(x,y):
return x*y
L1=([1,2,4,6])
L2=(reduce(prod,L1))

print(L2)

L2=list(reduce(prod,L1))不正确,因为L2是整型,前面要去掉list。


问题:利用mapreduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456:(参考)

from functools import reduce
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,[x for x in s[n+1:]]))
return reduce(fn,s1)+reduce(fn,s2)/10**len(s2)
print("\"123.4567\"=",str2float("123.4567"))


猜你喜欢

转载自blog.csdn.net/weixin_41887402/article/details/79813914