from functools import reduce
def normalize(name): return str(name).capitalize()
# return str(name)[0:1].upper() + str(name)[1:].lower()
L1 = ['adam', 'LISA', 'barT'] L2 = list(map(normalize, L1)) print(L2)
def prod(L): return reduce(lambda x, y: x * y, L)
print('3 5 7 * 9 =', prod([3, 5, 7, 9]))
def str2float(s): 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]
sp = s.split(".") n = len(sp[1]) result = reduce(lambda x, y: x * 10 + y, map(str2num, sp[0])) if '.' in s: result += reduce(lambda x, y: x * 10 + y, map(str2num, sp[1])) / (10 ** n) return result
print('str2float(\'123.456\') =', str2float('123.456'))
Sign in to make a reply
Pop_林肥強
导入
from functools import reduce
利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']:
def normalize(name): return str(name).capitalize()
L1 = ['adam', 'LISA', 'barT'] L2 = list(map(normalize, L1)) print(L2)
Python提供的sum()函数可以接受一个list并求和,请编写一个prod()函数,可以接受一个list并利用reduce()求积:
def prod(L): return reduce(lambda x, y: x * y, L)
print('3 5 7 * 9 =', prod([3, 5, 7, 9]))
利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456:
def str2float(s): 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]
print('str2float(\'123.456\') =', str2float('123.456'))