python3中map()和reduce()函数的使用

  1. 利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入:[‘adam’, ‘LISA’, ‘barT’],输出:[‘Adam’, ‘Lisa’, ‘Bart’]
#方法一
>>> def normalize(L):
    return list(map(lambda name: str.title(name), L))

>>> normalize(['adam', 'LISA', 'barT'])
['Adam', 'Lisa', 'Bart']

#方法二

>>> def lower2upper(L):
	return list(map(lambda s:s[0:1].upper()+s[1:].lower(),L))

>>> lower2upper(['adam', 'LISA', 'barT'])
['Adam', 'Lisa', 'Bart']

#方法三
>>> def normalize(L):
    return list(map(lambda name: str.capitalize(name), L))

>>> normalize(['adam', 'LISA', 'barT'])
['Adam', 'Lisa', 'Bart']
>>> 
  1. Python提供的sum()函数可以接受一个list并求和,请编写一个prod()函数,可以接受一个list并利用reduce()求积
>>> from functools import reduce
>>> def prod(L):
    return reduce(lambda x, y: x * y, L)

>>> prod([1,2,3,4,5])
120
  1. 利用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}
>>> def char2num(s):
    # 字符串转换成数字
    return DIGITS[s]

>>> def fn(x, y):
    # 将序列变换成整数
    return x*10 + y

>>> def str2float(s):
    f_before = s.split('.')[0]        # 小数点前面的数字
    f_end = s.split('.')[1]            # 小数点后面的数字
    
    return reduce(fn, map(char2num, f_before)) + reduce(fn, map(char2num, f_end))/1000

>>> print(str2float('123.456'))
123.456

参考:https://www.cnblogs.com/telder/p/9166426.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值