• Python高级教程-Map/Reduce


    Python中的map()和reduce()

    Python内建了map()和reduce()函数。

    map()

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

    举例说明,有一个函数f(x)=X^2,要把这个函数作用在一个list[1,2,3,4,5,6,7,8,9]上,就可以用map()实现:

    >>> def f(x):
        return x*x
    
    >>> map(f,[x for x in range(1,10)])
    [1, 4, 9, 16, 25, 36, 49, 64, 81]

    map()传入的第一个参数是f,即函数对象本身。

    map()作为高阶函数,事实上它把运算规则抽象了,因此,可以计算任意复杂的函数,比如把list的所有数字转为字符串:

    >>> map(str,[x for x in range(1,10)])
    ['1', '2', '3', '4', '5', '6', '7', '8', '9']

    reduce()

    reduce把一个函数作用在一个序列[x1,x2,x3,............]上,这个函数必须接受两个参数,reduce把结果继续和序列的下一个元素做积累计算,其效果就是:

    reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)

    比方说对一个序列求和,就可以用reduce实现:

    >>> def add(x,y):
        return x+y
    
    >>> reduce(add,[x for x in range(1,101)])
    5050
    >>> 

    当然求和运算可以直接用Python内建函数sum(),没必要动用reduce。

    但是如果把序列[1,3,5,7,9]变换成整数13579,reduce就可以派上用场:

    >>> def f(x,y):
        return x*10+y
    
    >>> reduce(f,[x for x in range(1,10) if x%2!=0])
    13579

    这个例子本身没大用处,但是,如果考虑到字符串str也是一个序列,对上面的例子稍加改动,配合map(),即可以把str转换为int的函数:

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

    整理成一个str2int的函数是:

    >>> def str2int(s):
        def fn(x,y):
            return x*10 + y
    
        
    >>> def str2int(s):
        def fn(x,y):
            return x*10 + y
        def char2num(s):
            return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
        return reduce(fn,map(char2num,s))
    
    >>> str2int('1234567')
    1234567

    还可以用lambda函数进一步简化成:

    >>> def char2num(s):
        return{'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
    
    >>> def str2int(s):
        return reduce(lambda x,y:x*10+y , map(char2num,s))
    
    >>> str2int('13579')
    13579
  • 相关阅读:
    详解Python模块导入方法
    第15天上课例子,sqllchemy运用
    【Demo 0075】获取系统进程列表
    【Demo 0076】获取进程中模块列表
    【Demo 0071】托盘小工具
    【Demo 0070】读取EXE\DLL中ICON
    【Demo 0073】复合文件拼拆
    【Demo 0072】启动外部应用程序
    【Demo 0078】获取系统版本信息
    【Demo 0079】进程继承关系
  • 原文地址:https://www.cnblogs.com/fangpengchengbupter/p/7755622.html
Copyright © 2020-2023  润新知