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)
  • 相关阅读:
    IO
    mouseover,mouseout和mouseenter,mouseleave
    【译】addEventListener 第二个参数
    Git 常用命令
    我对Backbone中url属性的理解
    小失误引起大失败
    收集各大网站的登录页面
    随笔2
    随笔1
    创建数据库
  • 原文地址:https://www.cnblogs.com/ShanCe/p/9326319.html
Copyright © 2011-2022 走看看