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)

 

posted @ 2018-07-17 22:16  ShanCe-刘勇  阅读(305)  评论(0编辑  收藏  举报