码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-07-09 20:59:23      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:log   ret   opened   from   port   float   class   mic   nbsp   

 

1. 利用mapreduce编写一个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连用实例

标签:log   ret   opened   from   port   float   class   mic   nbsp   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!