zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    接口
    多态
    封装
    初识继承
    对象的行为
    类、对象、包
    Java方法
    winform 报表的基本使用
    oracle配合C#的使用
    sql面试语句与后台调用js提示语句
  • 原文地址:https://www.cnblogs.com/ShanCe/p/9326319.html
Copyright © 2011-2022 走看看