初学python练习:map和reduce的使用
第一题:将用户输入的不规范英文名,转换为规范英文名,即首写字母为大写,其余为小写
def normalize(name1) :
return name1.title()
name = ''
L1 = []
while name!='exitt':
name = input('请输入用户名')
L1.append(name)
L2 = list(map(normalize,L1))
print(L1)
print(L2)
第二题:请编写一个prod()函数,可以接受一个list并利用reduce()求积:
from functools import reduce
def prod(L):
def multi(x,y):
return x*y
return reduce(multi,L)
L = [1,2,5]
L1 = prod(L)
print(L1)
第三题:(字符串可随意变动,均可输出)利用map和reduce编写一个str2float函数,把字符串’123.456’转换成浮点数123.456
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9,'.': '.'}
from functools import reduce
def str2float(str1):
def _operate(x,y):
return 10*x+y
def trans1(x):
return DIGITS[x]
L1 = list(map(trans1,str1))
point_position = L1.index('.')
L_interal = []
L_decimal = []
n=0
while n<len(L1):
if(n<point_position):
L_interal.append(L1[n])
elif n==point_position:
pass
else:
L_decimal.append(L1[n])
n=n+1
len_decimal = len(L_decimal)
L_I=reduce(_operate,L_interal)
L_D=reduce(_operate,L_decimal)
L_value = L_I+L_D/(10**len_decimal)
return L_value
_str = '12313.23'
print(str2float(_str))
题目来源
[ 廖雪峰的官方网站]