zoukankan      html  css  js  c++  java
  • python高阶函数

    1. 实际应用
    # 1. 两个list的相加
    a=[1,2,3]
    b=[4,5,6]
    现将list a与 list b按位相加,其结果为[5,7,9]
    
    方法一:
    c=[a[i]+b[i] for i in range(min(len(a),len(b)))]
    
    方法二:【map()函数,zip()函数】
    c=list(map(lambda x :x[0]+x[1] ,zip(a,b)))
    
    方法三:
    import numpy as np
    c = np.array(a) + np.array(b)
    
    
    
    # 2. 求True的最大值,false的最小值
    tuple_list = [(True,11),(True,12),(False,22),(False,32),(True,52),(True,2),]
    方法1:一不小心的神操作
    res_max = max(tuple_list) 
    res_min = min(tuple_list) 
    
    方法2:
    res = max(tuple_list)  # (True, 52)
    res = max(tuple_list,key=lambda x:~x[0])  # (False, 22)
    res = max(tuple_list,key=lambda x:(~x[0],x[1]))  # (False, 32)
    
    方法3:
    # new_start = max([i.get()[1] for i in result_dic.values() if i.get()[0]])
    # new_end = min([i.get()[1] for i in result_dic.values() if not i.get()[0]])
    
    1. 高阶函数,接收函数作为参数,或者将函数作为返回值的函数是高阶函数;

    2. 5个带key内置函数

      • 1.filter/map(function, iterable) --> 迭代器

      • 2.sorted(iterable[, cmp[, key[, reverse]]]) --> list

      • 3.min/max(iterable, *[, default=obj, key=func]) --> value

      • 下面的两个不是:但是常用

      • enumerate(sequence, [start=0])

      • zip([iterable, ...])

    3. 这类函数总结

    a = [1,2,3,1,1,1,3,3,3,3]
    
    #1
    print(max(a,key=a.count))   # a.count(3) = 5
    
    #2 上面的等价于
    l ={}
    for i in a:
        l[a.count(i)]=i
    res_num = max(l)
    res_id = l[res_num]
    print(l)
    print(res_num,res_id)
                
    
    
    1. max
    
    #count函数先理解
    a = [1,2,3,3,2,2,2,2]
    print(a.count(2)) # 5
    print(max(set(a),key=a.count)) #2
    
    
    # max() 方法返回给定参数的最大值,参数可以为序列。
    lis = [1,2,3,-4]
    print(max(lis)) #返回lis列表中的最大值  # 3
    print(max(lis,key=abs)) #key参数指向绝对值函数,返回的结果是-4
    
    1. min
    #(2)min
    # min() 方法返回给定参数的最小值,参数可以为序列。
    lis = [-1,0,1,2]
    print(min(lis)) #返回lis列表中的最小值 # -1
    
    
    1. fileter
    '''
    unittest源码中
    '''
        def getTestCaseNames(self, testCaseClass):
            """Return a sorted sequence of method names found within testCaseClass
            """
            #这里定义filter函数
            def shouldIncludeMethod(attrname):
                if not attrname.startswith(self.testMethodPrefix):
                    return False
                testFunc = getattr(testCaseClass, attrname)
                if not callable(testFunc):
                    return False
                fullName = f'%s.%s.%s' % (
                    testCaseClass.__module__, testCaseClass.__qualname__, attrname
                )
                return self.testNamePatterns is None or 
                    any(fnmatchcase(fullName, pattern) for pattern in self.testNamePatterns)
    
            #filter 使用方法
            testFnNames = list(filter(shouldIncludeMethod, dir(testCaseClass)))
    
            #是否排序
            if self.sortTestMethodsUsing:
    
                #testFnNames是列表,sort是python3里面的列表方法
                #case的排序
                testFnNames.sort(key=functools.cmp_to_key(self.sortTestMethodsUsing))
            return testFnNames
    
    
    # filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象。
    # 该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,最后将返回
    # True 的元素放到新列表中。
    
    # 语法格式:filter(function, iterable)
    
    #实例1
    def is_odd(x):
        return x % 2 == 1
    print(list(filter(is_odd,[1,2,3,4,5,6,7,8,9]))) #python3中不使用list强转数据类型的话,filter返回的是迭代器
    '''结果:
    [1, 3, 5, 7, 9]
    '''
    
    #实例2
    s = 'jason lv'
    iterator = filter(lambda x : x !='a',s)
    s1 = ''
    for i in iterator:
        s1 += str(i)
    print(s1)
    '''结果:
    json lv
    '''
    
    
    # 不是常用 20210727
    # 字符串拼接
    
    FirstName = 'f'
    # LastName = None
    LastName = 'l'
    
    FullName = ', '.join(filter(None, (LastName, FirstName)))
    
    print(FullName)
    # f
    # l, f
    
    
    1. map
    # map() 会根据提供的函数对指定序列做映射。
    # 第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回一个迭代器对象。
    
    # 语法格式:map(function, iterable, ...)
    
    #实例1
    def pow2(x):
        return x * x
    
    lis = [1,2,3,4,5,6]
    print(list(map(pow2,lis)))
    '''结果:
    [1, 4, 9, 16, 25, 36]
    '''
    
    #实例2
    lis = [1,2,3,4,5,6]
    print(list(map(lambda x : x *10 if x >3 else x / 2,lis)))
    '''结果:
    [0.5, 1.0, 1.5, 40, 50, 60]
    '''
    
    #碰到
    iterm = ['1','2','3']
    print(','.join(iterm))
    # 上面等价于
    iterm = [1,2,3]
    print(','.join(map(str,iterm)))
    
    '''
    unittest源码中
    '''
        def loadTestsFromTestCase(self, testCaseClass):
            """Return a suite of all test cases contained in testCaseClass"""        
            if issubclass(testCaseClass, suite.TestSuite):
                raise TypeError("Test cases should not be derived from "
                                "TestSuite. Maybe you meant to derive from "
                                "TestCase?")
            testCaseNames = self.getTestCaseNames(testCaseClass)
            if not testCaseNames and hasattr(testCaseClass, 'runTest'):
                testCaseNames = ['runTest']
    
            #map(function, iterable) 返回迭代器
            loaded_suite = self.suiteClass(map(testCaseClass, testCaseNames))
            return loaded_suite
    
    '''
    其他示例
    '''
    # 使用 lambda 匿名函数
    >>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])  
    [1, 4, 9, 16, 25]
     
    # 提供了两个列表,对相同位置的列表数据进行相加
    >>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
    [3, 7, 11, 15, 19]
    
    1. sorted 注意不是Sort,Sort函数是list列表中的函数
    • sort 与 sorted 区别:(注意sort 没有返回值的坑)
    • sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。
    • list 的 sort 方法返回的是对已经存在的列表进行操作,无返回值,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。
    #(5)sorted
    # Sort函数是list列表中的函数,而sorted可以对list或者iterator进行排序。
    
    # 语法格式:sorted(iterable[, cmp[, key[, reverse]]])
    # 参数说明:
    # (1) cmp参数
    # cmp接受一个函数,拿整形举例,形式为:
    # def f(a, b):
    #     return a - b
    #
    # 如果排序的元素是其他类型的,如果a逻辑小于b,函数返回负数;a逻辑等于b,函数返回0;a逻辑大于b,函数返回正数就行了
    # (2)key参数
    # key也是接受一个函数,不同的是,这个函数只接受一个元素, 形式如下
    # def f(a):
    #     return len(a)
    #
    # key接受的函数返回值,表示此元素的权值,sort将按照权值大小进行排序
    #
    # (3)reverse参数
    # 接受False
    # 或者True
    # 表示是否逆序
    
    # 语法格式:sorted(iterable[, cmp[, key[, reverse]]])
    #实例1
    lis = [3,2,1,4,5,6]
    print(list(sorted(lis,reverse=True)))
    '''结果
    [6, 5, 4, 3, 2, 1]
    '''
    
    print(list(sorted(lis)))    #默认不指定reverse参数时,顺序是正序
    '''结果
    [1, 2, 3, 4, 5, 6]
    '''
    
    #实例2
    lis = ['adf ee','zcv','qwer','a s s w']
    print(list(sorted(lis,key=len)))
    '''结果:
    ['zcv', 'qwer', 'adf ee', 'a s s w']
    '''
    
    
    # robot源码
      def __iter__(self):
          print('##',self._keys)
          print('##',sorted(self._keys))
          return (self._keys[norm_key] for norm_key in sorted(self._keys))
    '''打印
    ## {'d': 'd', 'b': 'b', 'c': 'C'}
    ## ['b', 'c', 'd'] 【注意返回的是列表】
    '''
    
    
    
  • 相关阅读:
    C#中yield return用法
    vs生成命令和属性的宏
    开源的库RestSharp轻松消费Restful Service
    【C#】工具类-FTP操作封装类FTPHelper
    常见编码bug
    用Redis存储Tomcat集群的Session(转载)
    session转载
    pv,uv
    cookie读取设置name
    转载cookie理解
  • 原文地址:https://www.cnblogs.com/amize/p/14599977.html
Copyright © 2011-2022 走看看