首页 > 编程语言 > 详细

[ Python - 9 ] 高阶函数map和reduce连用实例

时间:2017-07-09 20:35:01      阅读:276      评论:0      收藏:0      [点我收藏+]

 

1. 利用map和reduce编写一个str2float函数,把字符串‘123.456‘转换成浮点数123.456:

技术分享
from functools import reduce
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]

def str2float(s):
    if ‘.‘ in s:
        # 将字符串s拆分成list类型
        s = s.split(‘.‘)
        # 通过小数点分割,分别计算然后相加
        return reduce(lambda x, y: x*10+y, map(str2num,s[0])) + reduce(lambda x, y: x/10+y, map(str2num, s[1][::-1]))/10
    else:
        return  reduce(lambda x, y: x*10+y, map(str2num, s))
s1 = str2float(‘123.456‘)
print(s1)
View Code

 

2. 编写一个函数,可以接受一个list并利用reduce()求积:

 

技术分享
def prod(L):
    def num(x, y):
        return x*y
    return reduce(num, L)

L = [1,2,3,4]
print(prod(L))
View Code

 

[ Python - 9 ] 高阶函数map和reduce连用实例

原文:http://www.cnblogs.com/hukey/p/7142531.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!