码迷,mamicode.com
首页 > 其他好文 > 详细

reduce

时间:2018-07-17 23:14:14      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:字符串   lamdba   tools   reduce   red   res   方法   利用   ace   

  • 在python2中可以直接用在python3中要导入模块
  • 整体数据进行压缩,合并得到一个最终结果
  • from functools import reduce

    reduce(<函数/处理方法>,<可迭代的>,<初始值/可有可无>)

from functools import reduce

li = [1,2,3]

print(reduce(lamdba x, y:x + y,li))

print(reduce(lamdba x, y: x + y,li,5)#设置初始值为5

print(reduce(lamdba x, y: x*10+y,li)#结果123
#利用map和reduce编写一个str2float函数,把字符串‘123.456‘转换成浮点数123.456:
from functools import reduce

s = "123.456"


def map_list(n):
    digits = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9}
    return map(lambda x: digits[x], n.replace(., ‘‘))


def str_float(a):
    return reduce(lambda x, y: x * 10 + y, map_list(a)) / (10 ** a.index(.))


# res = reduce(lambda x,y:x*10+y ,map(lambda x: digits[x], s.replace(‘.‘,‘‘)))/(10**s.index(‘.‘))
print(str_float(s))


######################合并
digits = {‘0‘: 0, ‘1‘: 1, ‘2‘: 2, ‘3‘: 3, ‘4‘: 4, ‘5‘: 5, ‘6‘: 6, ‘7‘: 7, ‘8‘: 8, ‘9‘: 9}
res = reduce(lambda x,y:x*10+y ,map(lambda x: digits[x], s.replace(‘.‘,‘‘)))/(10**s.index(‘.‘))
print(res)

 

reduce

标签:字符串   lamdba   tools   reduce   red   res   方法   利用   ace   

原文地址:https://www.cnblogs.com/ShanCe/p/9326319.html

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