reduce

  • 在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)

 

转载于:https://www.cnblogs.com/ShanCe/p/9326319.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值