zoukankan      html  css  js  c++  java
  • map函数和reduce函数

    一、map函数

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

    例如:

    >>> def f(x):
    	return x*x
    
    >>> l=[1,2,3,4,5,6,7,8,9]
    >>> r=map(f,l)
    >>> r
    <map object at 0x0000028C820326A0>
    >>> list(r)
    [1, 4, 9, 16, 25, 36, 49, 64, 81]
    

      

    二、reduce函数

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

    其效果为:

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

      

    例如,对一个序列求和:

    >>> from functools import reduce
    >>> def add(x,y):
    	return x+y
    
    >>> reduce(add,[1,2,3,4,5])
    15
    

      

    三、相关练习题

    1.  利用 map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字

    >>> def norm(name):
    	return name[0].upper()+name[1:].lower()
    
    >>> L=['monica','phoebe','rachel','ross']
    >>> n=map(norm,L)
    >>> list(n)
    ['Monica', 'Phoebe', 'Rachel', 'Ross']
    

      

      

    2.  编写一个 prod()函数,可以接受一个list并利用 reduce()求积

    >>> from functools import reduce
    >>> def prod(L):
    	return reduce(lambda x,y:x*y,L)
    
    >>> prod([1,2,3,4,5])
    120
    

      

      

    3.  利用 map和 reduce 编写一个 str2float 函数,把字符串'123.456'转换成浮点数 123.456

    from functools import reduce
    
    def str2float(s):
        digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
        pointIndex=-1
        for i in range(0,len(s)):
            if ord(s[i]) == 46:
                pointIndex=i
                break
        if pointIndex >0:
            return reduce(lambda x,y:x*10+y,list(map(lambda z:digits[z],s[:pointIndex]+s[pointIndex+1:])))/(10**pointIndex)
        else:
            return reduce(lambda x,y:x*10+y,list(map(lambda z:digits[z],s)))
    

      

  • 相关阅读:
    【U-Boot】建立U-Boot编译环境
    【电路】JTAG下载器研究
    【FPGA】Xilinx-7系的时钟资源与DDR3配置
    【电路】KiCad-Pcbnew-建BGA形式的Footprint
    【电路】KiCad-Eeschema-建BGA形式的Symbol
    【电路】差分接口互连(二)
    【电路】差分接口互连(一)
    【电路】pmic芯片设计细节
    【电路】PADS建库细节
    【电路】SPI接口细化&控制
  • 原文地址:https://www.cnblogs.com/canneddream/p/14206815.html
Copyright © 2011-2022 走看看