zoukankan      html  css  js  c++  java
  • python之高阶函数(map/reduce)

    map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。

    map()函数接收两个参数,一个是函数,一个是Iterable

    实例

    # def f(x):
    #     return x * x
    # a=[1,2,3,4,5,6,7,8,9]
    # r=map(f,a)  # 将a中的元素分别带入到函数中
    # print(list(r))

     reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数

    实例:求和

    # from  functools import reduce
    # def f(x,y):
    #     return x + y
    # a=[1,2,3,4,5,6,7,8,9]
    # r=reduce(f,a)
    # print(r)

     

    reduce常用来做累计计算

    将不规范的英文变为首字母大写

    # def dx(name):
    #     return name.title()
    # L1 = ['adam', 'LISA', 'barT']
    # L2 = list(map(dx, L1))
    # print(L2)

     累计求积

    # from  functools import reduce
    # def f(x,y):
    #     return x * y
    # a=[1,2,3,4,5,6,7,8,9]
    # r=reduce(f,a)
    # print(r)

     将字符串转换乘浮点数

    # from  functools import reduce
    # def def1(x):# 定义函数
    #     digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9,'.':'.'}#定义字典
    #     return digits[x] #输出对应的值
    # p=0
    # m=1
    # def def2(x,y):#定义函数
    #     if y=='.':
    #         global p
    #         p=1
    #         return x
    #     if p==0:
    #         return x * 10 + y
    #     else:
    #         global m
    #         m=m*0.1
    #         return x+y*m
    # print(reduce(def2,map(def1,'24234.32423')))

  • 相关阅读:
    【bzoj1036】【ZJOI2008】树的统计
    AE基础(8)PageLayout属性设置和添加元素
    AE基础(7)布局控件与地图控件关联
    UtilityAction扩展
    UtilityAction
    AE基础(6)数据查询与选择
    NavigationAction
    LayerAction
    AE基础(5)鹰眼功能
    AE基础(4)画几何图形
  • 原文地址:https://www.cnblogs.com/wbf980728/p/14053375.html
Copyright © 2011-2022 走看看