Python小练习 (2)

作者: Stone_説 | 来源:发表于2021-02-06 23:04 被阅读0次

    自定义sort函数

    1. 源码实现sort函数
    def sort(self, key=None, reverse=False): # real signature unknown; restored from __doc__
        """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """
        pass
    key参数表示排序的规则,可传入一个函数
    reverse表示是否反序,传入True或False
    
    2. 基本功能的实现
    def sort(iterable,*,key=None,reverse=False):
        newlist = []
        for x in iterable:
            for i,y in enumerate(newlist):
                if x>y:
                    newlist.insert(i,x)
                    break
            else:
                newlist.append(x)
        return newlist
    
    lst = [43,1,5,23,12,10]
    print(1,lst)
    print('*'*30)
    print(2,sort(lst))
    
    # 程序运行结果
    1 [43, 1, 5, 23, 12, 10]
    ******************************
    2 [43, 23, 12, 10, 5, 1]
    
    3. reverse参数的实现
    def sort(iterable,*,key=None,reverse=False):
        newlist = []
        for x in iterable:
            for i,y in enumerate(newlist):
                comp = x > y if reverse else x < y
                if comp:
                    newlist.insert(i,x)
                    break
            else:
                newlist.append(x)
        return newlist
    
    lst = [43,1,5,23,12,10]
    print(1,lst)
    print('*'*30)
    print(2,sort(lst))
    
    # 程序运行结果
    1 [43, 1, 5, 23, 12, 10]
    ******************************
    2 [1, 5, 10, 12, 23, 43]
    
    4. key参数的实现
    def sort(iterable,*,key=lambda x:6-x,reverse=False):
        newlist = []
        for x in iterable:
            cx = key(x) if key else x
            for i,y in enumerate(newlist):
                cy = key(y) if key else y
                comp = cx > cy if reverse else cx < cy
                if comp:
                    newlist.insert(i,x)
                    break
            else:
                newlist.append(x)
        return newlist
    
    lst = [43,1,5,23,12,10]
    print(1,lst)
    print('*'*30)
    print(2,sort(lst))
    
    # 程序运行结果
    1 [43, 1, 5, 23, 12, 10]
    ******************************
    2 [43, 23, 12, 10, 5, 1]
    

    filter函数介绍

    lst1 = [100,42,3,5,45,23,65]
    lst = list(filter(lambda x: x%3==0,lst1))
    print(1,lst)
    print(2,list(filter(None,range(5))))
    print(3,list(filter(None,range(-5,5))))
    
    # 程序运行结果
    1 [42, 3, 45]
    2 [1, 2, 3, 4]
    3 [-5, -4, -3, -2, -1, 1, 2, 3, 4]
    

    映射map函数介绍

    lst1 = [100,42,3,5,45,23,65]
    print(1,list(map(lambda x:2*x+1,lst1)))
    print(2,dict(map(lambda x:(x%5,x),range(500))))
    print(3,dict(map(lambda x,y:(x,y),'abcde',range(10))))
    
    # 程序运行结果
    1 [201, 85, 7, 11, 91, 47, 131]
    2 {0: 495, 1: 496, 2: 497, 3: 498, 4: 499}
    3 {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4}
    

    相关文章

      网友评论

        本文标题:Python小练习 (2)

        本文链接:https://www.haomeiwen.com/subject/imlatltx.html