• 匿名函数,高阶函数,和内置函数


    一·匿名函数

    没有函数名,函数调用后,直接把该函数的内存空间回收。减少了内存空间的使用。

    定义方式:

    lambda x:x+1   #第一个x为参数,x+1为返回的值。

    使用方式:

    func=lambda x:x+1
    print(func(10))
    #func变量获取了匿名函数的地址,然后在通过发送一个变量10调用匿名函数

    二·python中的内置函数

    1.map

    
    

      def add_one(x):
          return x+1

      def map_test(func,array): #func=lambda x:x+1 arrary=[1,2,10,5,3,7]

        ret=[]
        for i in array:
            res=func(i) #add_one(i)
            ret.append(res)
        return ret
    print(map_test(add_one,num_l))
    #map_test: map函数的原理,传入一个函数的函数名(内存地址)和一个可迭代对象,可迭代对象中的数据经过map的处理,然后返回给一个ret列表。
    
    res=map(lambda x:x+1,num_l)
    #map把map_test的代码封装,减少了代码量

    2. reduce函数

    from functools import reduce

      num_l=[1,2,3,100]

    def reduce_test(func,array,init=None):
        if init is None:
            res=array.pop(0)
        else:
            res=init
        for num in array:
            res=func(res,num)
        return res
    
    print(reduce_test(lambda x,y:x*y,num_l,100))
    print(reduce(lambda x,y:x+y,num_l,1))
    print(reduce(lambda x,y:x+y,num_l))
    
    #reduce的作用就是返回可迭代对象被函数(所有元素一同运算)运算后的结果

     3.filter函数

    movie_people=['alex_sb','wupeiqi_sb','linhaifeng','yuanhao_sb']
    
    def filter_test(func,array):
        ret=[]
        for p in array:
            if not func(p):
                   ret.append(p)
        return ret
    
    res=filter_test(lambda n:n.endswith('sb'),movie_people)
    print(res)
    
    #filter函数
    movie_people=['alex_sb','wupeiqi_sb','linhaifeng','yuanhao_sb']
    print(filter(lambda n:not n.endswith('sb'),movie_people))
    #使用filter函数过滤掉符合函数中条件的元素,并使用列表返回剩下的元素

    上面三个是最主要的内置函数

    5.id()

    print(id(1))   #返回对象的地址

    6. abs()

    print(abs(-1))  返回元素的绝对值
  • 相关阅读:
    [笔记]一道C语言面试题:IPv4字符串转为UInt整数
    linux内核代码注释 赵炯 第三章引导启动程序
    bcd码
    2章 perl标量变量
    1章 perl入门
    perl第三章 列表和数组
    浮动 float
    文字与图像
    3.深入理解盒子模型
    4.盒子的浮动和定位
  • 原文地址:https://www.cnblogs.com/ithome0222/p/8678872.html
Copyright © 2020-2023  润新知