• 内置函数二 & 递归 & 二分查找


    主要内容:

    • 1. lamda匿名函数
    • 2. sorted()
    • 3. filter()
    • 4. map()
    • 5. 递归函数
    • 6.  二分查找.

    1.lamda匿名函数

       为了解决⼀些简单的需求而设计的⼀句话函数,   语法: 函数名 = lambda 参数: 返回值

    • 函数的参数可以有多个, 多个参数之间用逗号隔开
    • 匿名函数不管多复杂. 只能写一行, 且逻辑结束后直接返回数据
    • 返回值和正常的函数一样, 可以是任意数据类型
    zed= lambda a,b : a+b
    ret=zed(2,3)
    print(ret)

    2. sorted()排序函数.

        语法: sorted(Iterable, key=None, reverse=False)

    • Iterable: 可迭代对象 
    • key: 排序规则(排序函数), 在sorted内部会将可迭代对象中的每⼀个元素传递给这个函数的参数. 根据函数运算的结果进行排序
    • reverse: 是否是倒序. True: 倒序, False: 正(不写,默认正序)
    lst=["天龙八部","倚天屠龙记","鹿鼎记","雪山飞狐","功夫","射雕英雄传"]
    def func(name):
        return len(name)
    l1 = sorted(lst,key=func)
    print(l1)
    lst=["天龙八部","倚天屠龙记","鹿鼎记","雪山飞狐","功夫","射雕英雄传"]
    l2 = sorted(lst,key=lambda name:len(name)%3)              #sorted与lambda配合使用
    print(l2)
    lst = [{"id": 1, "name": 'alex', "age": 18},
        {"id": 2, "name": 'wusir', "age": 16},
        {"id": 3, "name": 'taibai', "age": 17}]
    # 按照年龄对学⽣信息进⾏排序
    def func(dic):
        return dic['age']
    l2 = sorted(lst, key=func)         # 流程: 把可迭代对象的每一项传递给函数. 函数返回一个数字. 根据这个数字完成排序
    print(l2)
    l3 = sorted(lst, key=lambda dic: dic['age'])
    print(l3)
    l4 = sorted(lst, key=lambda dic: len(dic['name']))                      #按照名字长度排序
    l5 = sorted(lst, key=lambda dic: ascii(dic['name'][0]))  # ord()        #按照名字ascii排序
    print(l4)
    print(l5)

    3. filter()筛选函数

        语法: filter(function. Iterable)

    • function: 用来筛选的函数, 在filter中会自动的把iterable中的元素传递给function. 然后根据function返回的True或者False来判断是否保留此项数据       
    • Iterable: 可迭代对象 
    lst = [23, 28, 15, 27, 24, 22]
    def func(age):
        return age > 18 and age % 2 == 0
    f = filter(func, lst)
    print("__iter__"in dir(f))                  #判断f是否为可迭代对象  True
    print(list(f))                              #  [28, 24, 22]           
    lst = [23, 28, 15, 27, 24, 22]
    print(list(filter(lambda age:age >18 and age % 2 ==0,lst)))
    lst = [23, 28, 15, 27, 24, 22]
    f = filter(lambda age: age > 18 and age % 2 == 0, lst)
    print(list(f))                      #  [28, 24, 22]
    print(sorted(f))                    #[]                  迭代器的惰性机制
    lst = [23, 28, 15, 27, 24, 22]
    f = filter(lambda age: age % 2 == 0, filter(lambda age: age > 18, lst))
    print(list(f))
    lst = [{"id":1, "name":'alex', "age":18},
     {"id":2, "name":'wusir', "age":16},
     {"id":3, "name":'taibai', "age":17}]
    
    # 筛选出年龄大于等于17岁的人,并按照年龄排序
    f1=filter(lambda dic: dic['age'] >= 17, lst)
    f2=sorted(f1, key=lambda dic: dic['age'])
    print(list(f2))            #[{'id': 3, 'name': 'taibai', 'age': 17}, {'id': 1, 'name': 'alex', 'age': 18}]
    # print(list(sorted(filter(lambda dic: dic['age'] >= 17, lst), key=lambda dic: dic['age'])))
     

    4. map()  映射函数

     语法: map(function, iterable) 可以对可迭代对象中的每一个元素进行映射,分别取执行 function 

    lst = [1,5,9,3]
    # l1 = [i**2 for i in lst]
    m = map(lambda x: x**2, lst)
    print(list(m))

    计算两个列表中相同位置的数据的和

    lst1 = [1, 2, 3, 4, 5]
    lst2 = [2, 4, 6, 8, 10]
    print(list(map(lambda x, y: x + y , lst1, lst2)))          #[3, 6, 9, 12, 15]

    5. 递归函数

    在函数中调用函数本身. 就是递归, (在python中递归的深度最大为1000,但实际到998)

    def func():
        print("你好")
        func()
    func()

    递归的应用:

       (1) 我们可以使用递归来遍历各种树形结构比如我们的文件夹系统.,可以使用递归来遍历该文件夹中的所有文件

    import os
    def func(file_path,n):
        lst=os.listdir(file_path)  # 得到文件夹里的所有文件和文件夹
        for file in lst:
            full_path = os.path.join(file_path, file)      # 获取到文件的全路径
            if os.path.isdir(full_path):                   # 判断这个路径是否是一个文件夹
                print("	"*n,file)
                func(full_path,n+1)                        # 继续进行相同的操作
            else:
                print("	"*n,file)                         # 递归出口. 最终在这里隐含着return
    func("G:",0)

     6. 二分查找

        每次能够排除掉⼀半的数据,查找的效率非常高,但是局限性比较大,必须是有序列才可以使用二分查找     要求: 查找的序列列必须是有序列.

    #递归的第一套排序
    lst = [1, 1, 1, 1, 2, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 7, 8, 8, 9, 16, 32, 44, 55, 78, 89]
    def func(n,lst):
        left = 0
        right = len(lst)-1
        if left <= right:
            mid = (left+right)//2
            if n > lst[mid]:
                New_lst =lst[mid+1:]
                return func(n,New_lst)
            elif n < lst[mid]:
                New_lst =lst[:mid]
                return func(n,New_lst)
            else:
                print("刚好在这里")
                return True
        else:
            return False
    ret=func(89,lst)
    print(ret)
    #递归的第二套排序
    lst = [1, 1, 1, 1, 2, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 7, 8, 8, 9, 16, 32, 44, 55, 78, 89]
    def func (n,lst,left,right):
        if left <= right:
            mid =(left+right)//2
            if n > lst[mid]:
                left=mid+1
                return func(n,lst,left,right)
            elif n < lst[mid]:
                right=mid-1                                #在此处注意与第一种方案的细微差别
                return func(n,lst,left,right)
            else :
                print("刚好在这里'")
                return True
        else :
            return False
    ret= func(89,lst,0,len(lst)-1)
    print(ret)
    #递归的第二套排序(改善)
    lst = [1, 1, 1, 1, 2, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 7, 8, 8, 9, 16, 32, 44, 55, 78, 89]
    def func (n,lst,left=0,right=len(lst)-1):                       #默认值参数
        # if right == None:
        #     right=len(lst)-1
        if left <= right:
            mid =(left+right)//2
            if n > lst[mid]:
                left=mid+1
                return func(n,lst,left,right)
            elif n < lst[mid]:
                right=mid-1                                #在此处注意与第一种方案的细微差别
                return func(n,lst,left,right)
            else :
                print("刚好在这里'",mid)
                return True
        else :
            return False
    ret= func(89,lst)
    print(ret)
  • 相关阅读:
    IDEA 快捷键
    Python3开启自带http服务
    redis-creating server tcp listening socket 127.0.0.1:6379: bind No error
    moco的使用方法
    tomcat程序闪退,如何让tomcat不闪退,可以看见报错
    java 项目中Error linstenerStart 报错解决方法
    Linux 常用命令
    TS数据类型及语法
    RabbitMQ的下载和安装
    vue 控制 input 的 disabled
  • 原文地址:https://www.cnblogs.com/wcx666/p/9681979.html
Copyright © 2020-2023  润新知