zoukankan      html  css  js  c++  java
  • Python(六) 高阶函数

    1.map/reduce

      map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。

      把函数f(x)=x*x作用于一个list序列

    def f(x):
        return x*x
    
    r=map(f,[1,2,3,4,5,6])
    print(list(r))

    控制台输出结果:

    [1, 4, 9, 16, 25, 36]

    map()传入的第一个参数是f(x)函数。函数返回结果是一个Iterator,是惰性序列。通过list()函数可将整个序列都计算出来并返回一个list。

      将list中所有数字转换为字符串

    s=list(map(str,[1,2,3,4,5]))
    print(s)

    控制台输出结果:

    ['1', '2', '3', '4', '5']

    2.reduce

      reduce把一个函数作用在一个序列,这个函数必须接受两个参数,reduce把结果继续和序列的下一个元素做计算

    from functools import reduce
    #序列求和
    def add(x,y):
        return x+y
    total=reduce(add,[1,2,3,4,5])
    print(total)
    #序列累积
    def mul(x,y):
        return x*y
    
    print(reduce(mul,[1,2,3]))

      用map(),reduce()把str转换成int的函数:

    from functools import reduce
    def fn(x,y):
        return x*10+y
    
    def char2num(s):
        digits={'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
        return digits[s]
    #字符串是一个序列
    strint=reduce(fn,map(char2num,'123456'))
    print(strint)

    控制台输出结果:

    123456

     整理成一个函数strtoint

    D={'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
    def strtoint(s):
        def fn(x,y):
            return x*10+y
        def char2num(s):
            return D[s]
        return reduce(fn,map(char2num,s))
    
    print(strtoint('23435'))

    控制台输出结果:

    23435

    用lambda函数进一步简化:

    D2={'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
    def char2num(s):
        return D2[s]
    def strtoint1(s):
        return reduce(lambda x,y:x*10+y,map(char2num,s))
    print(strtoint1('2342345235243'))

    控制台输出结果:

    2342345235243

  • 相关阅读:
    全文索引的书
    图片上传预览
    sqlserver 递归删除组织结构树
    dataset 转泛型list
    jquery easyui tree 异步加载数据
    sqlserver 禁用外键
    linx 实用操作命令二
    Compilation failed: this version of PCRE is not compiled with PCRE_UTF8 support at offset 0
    Centos linux php扩展安装步骤
    linux Apache和php配置
  • 原文地址:https://www.cnblogs.com/codeRose/p/8280609.html
Copyright © 2011-2022 走看看