1. 利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。
def normalize(name):
name = name.lower()
str1 = name[:1]
str2 = name[1:]
return str1.upper() + str2
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)
2. 请编写一个prod()函数,可以接受一个list并利用reduce()求积:
from functools import reduce
def prod(L):
def fn(x,y):
return x*y
return reduce(fn, L)
print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
if prod([3, 5, 7, 9]) == 945:
print('测试成功!')
else:
print('测试失败!')
3.利用map()和reduce()编写一个str2float函数,把字符串‘123.456’转换成浮点数123.456
from functools import reduce
Digits = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9}
def char_to_num(s):
str1, str2 = '', ''
pos = s.find('.')
if pos>-1:
str1 = s[:pos]
str2 = s[pos + 1:]
else:
str1 = s
def fn1(x,y):
return x*10+y
def char2num(s):
return Digits[s]
value1, value2 = 0, 0
if str1:
value1 = reduce(fn1, map(char2num, str1))
if str2:
value2 = reduce(fn1, map(char2num, str2))
value2 = value2 * pow(10, -len(str2))
return value1+value2
s = char_to_num('123.45')
print(s)