'''
利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。
输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']:
'''
def normalize(name):
return(name[0].upper() + name[1:].lower())
# 测试:
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)
#计算列表所有项乘积
from functools import reduce
def prod(L):
return(reduce(cheng,L))
def cheng(x,y):
return(x*y)
print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
if prod([3, 5, 7, 9]) == 945:
print('测试成功!')
else:
print('测试失败!')
#str2float 字符串‘123.456’转换为浮点型123.456
from functools import reduce
def str2float(s):
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
ls1,ls2 = s.split('.')
return(reduce(lambda x,y : x*10+y,map(lambda x : DIGITS[x],ls1)) + 0.1 * reduce(lambda x,y : x*0.1+y,map(lambda x : DIGITS[x],ls2[::-1])))
print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
print('测试成功!')
else:
print('测试失败!')
map/reduce
最新推荐文章于 2024-09-14 08:25:16 发布