python3.6.1
廖老师map/reduce后面的作业
1利用map()
函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入:['adam', 'LISA', 'barT']
,输出:['Adam', 'Lisa', 'Bart']
:
def normalize(name):
n=0
name1=list(name)
for i in name1:
if n is 0:
name1[n]=i.upper()
else:
name1[n]=i.lower()
n=n+1
return ''.join(name1)
>>> L1=['adam', 'LISA', 'barT']
>>> L2=list(map(normalize,L1))
>>> print(L2)
['Adam', 'Lisa', 'Bart']
Python为string对象提供了转换大小写的方法:upper() 和 lower()。
2Python提供的sum()
函数可以接受一个list并求和,请编写一个prod()
函数,可以接受一个list并利用reduce()
求积:
from functools import reduce
def prod(L):
def f(x,y):
return x*y
return reduce(f,L)
>>> print('3*5*7*9=',prod([3,5,7,9]))
3*5*7*9= 945
3利用map
和reduce
编写一个str2float
函数,把字符串'123.456'
转换成浮点数123.456
:
1.分割2.小数倒序3.相加
from functools import reduce
def str2float(s):
s1,s2=s.split('.')
s2=s2[::-1]
def f1(x,y):
return x*10+y
def f2(x,y):
return x*0.1+y
def char2num(s):
return {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}[s]
return reduce(f1,map(char2num,s1))+reduce(f2,map(char2num,s2))*0.1
>>> s='123.456'
>>> str2float(s)
123.456