• 内置函数二以及闭包


    内置函数二以及闭包

    1.内置函数二

    #abs()    求绝对值
    i = -5
    print(abs(i))    # 5
    
    #enumerate("可迭代对象",序号起始值(默认为0))   枚举    
    lst = [1,2,3]
    print([i for i in enumerate(lst,1) ])
                    #[(1, 1), (2, 2), (3, 3)]
        
    #max("可迭代对象",key = abs)  key指定查找最大值时的规则    求最大值
    print(max([1,2,3,4,5]))    # 5
    print(max([1,2,3,4,-5],key = abs))   # -5
    
    #min("可迭代对象",key = abs) key指定查找最小值时的规则    求最小值
    print(min([1,2,3,4,5]))   # 1
    print(min([1,2,3,4,-5],key = abs))    # 1
    
    #sum(list,tuple,set)  求和
    print(sum([1,2,3,4,5]))   # 15
    print(sum(((1,2))))        # 3
    print(sum({1,2,3,4,5}))    # 15
    
    #print()  输出
    print(sep=" ",end = "
    ")   sep为多个元素的连接符
    print(12345,file = open("t1.txt","w",encoding="utf-8"))
    
    #list(可迭代对象)  转换成列表
    print(list("alex"))  #['a','l','e','x']
    
    #dict()
    print(dict(key = 1,a = "alex"))  #{'key': 1, 'a': 'alex'}
    print(dict(((1,2),(3,4))))   #{1: 2, 3: 4}
    print(dict([i for i in enumerate(range(3),1)]))
    #  {1: 0, 2: 1, 3: 2}
    
    #zip("可迭代对象","可迭代对象") 拉链 --按照最少的进行合并
    print(list(zip((1,2),(3,4)))) #[(1, 3), (2, 4)]
    lst1 = [1,2,3,4]
    lst2 = ['a','b','c','d','e']
    print(dict(list(zip(lst1,lst2))))
            #{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
    print(dict(zip(lst1,lst2)))
            #{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
        
    #dir() 查看当前函数的方法
    print(dir(list))
    
    #len() 求长度
    #range() 范围
    #str()转换成字符串
    #set()转换成集合
    #open() 打开
    
    
    
    重要的内置函数和匿名函数
    #匿名函数
    def func(a,b):
        return a+b
    print(func(1,2))
    
    f = lambda x,y:x+y
    print(f(1,2))
    
    # lambda 关键字 --定义函数
    # x,y    形参
    # :x+y   返回值  --只能返回一个数据类型
    # 一行函数,形参可以不写,返回值必须要写,只能返回一个数据类型
    print((lambda x:x)(2))  同一行定义,同一行调用
    
    lst =[lambda i:i*i for i in range(10)]
    print(lst[2](2)
    即:
    lst = []
    for i in range(10):
        def func(i):
            return i*i
        lst.append(func)
    print(lst[2](2))    # 4
    
    lst = []
    for i in range(10):
        def func():
            return i*i
        lst.append(func)
    print(lst[2]())     # 81
    
    lst = list((lambda i:i**i for i in range(5)))
    print(lst[1](4))      #256
    lst = [x for x in (lambda :i**i for i in range(5))]
    print(lst[2]())       #256  #list的底层是for循环
    即:
    lst = []
    def func():
        for i in range(5):
            def foo():
                return i**i
            yield foo
    for x in func():
        lst.append(x)
    print(lst[2]())      # 256
    
    
    重要内置函数:
    # format()
    print(format(13,">20"))     #将13右对齐
    print(format(13,"<20"))     #将13左对齐
    print(format(13,"^20"))     #将13居中
    
    print(format(13,"08b"))     #将13转换成二进制并输出8位
    print(format(13,"08d"))     #将13转换成十进制并输出8位
    print(format(13,"08o"))     #将13转换成八进制并输出8位
    print(format(13,"08x"))     #将13转换成十六进制并输出8位
    
    #filter("函数名","可迭代对象")  过滤,写函数的时候可以指定过滤条件
    lst = [1,2,3,4,5,6]
    def func(s):
        return s>3
    print(list(filter(func,lst)))   # [4,5,6]
    #func就是自己定义一个过滤条件,lst就是要迭代的对象
    lst = [1,2,3,4,5,6]
    print(list(filter(lambda x:x>3,lst))) # [4,5,6]
    
    #map("函数名","可迭代对象")  映射,对可迭代对象中每个元素进行加工
    print(list(map(lambda x:x*x,[1,2,3,4,5])))
             # [1,4,9,16,25]
        
    #reversed("可迭代对象") 将一个序列反转,返回反转序列,不改变源数据
    lst = [1,2,3,4,5]
    print(list(reversed(lst)))  #[5,4,3,2,1]
    
    #sorted("可迭代对象",key = "函数名",reverse = True) key是指定排序的规则(默认升序),加reverse = True 则为反序
    lst = [1,4,3,2,5]
    print(sorted(lst))      # [1,2,3,4,5]
    lst = [1,4,3,2,5]
    print(sorted(lst,reverse = True))   #[5,4,3,2,1]
    
    dic = {"key1":1,"key2":2,"key3":15} #key是指定排序规则
    print(sorted(dic,key=lambda x:dic[x],reverse=True))
             #['key3', 'key2', 'key1']
        
    #reduce("函数","可迭代对象") 函数是指定累计算的方式
    from functools import reduce
    print(reduce(lambda x,y:x+y,[1,2,3,4,5]))  #15
    
    

    2.闭包

    在嵌套函数内,使用非全局变量(且不是本层变量)的就是闭包
    闭包的作用:
        1.保证数据的安全性
        2.装饰器
        
    avg_lst = []
    def func(pirce):
        avg_lst.append(pirce)
        avg = sum(avg_lst) / len(avg_lst)
        return avg
    print(func(150000))
    print(func(160000))
    print(func(170000))
    print(func(150000))
    
    错误:
    def func(pirce):
        avg_lst = []
        avg_lst.append(pirce)
        avg = sum(avg_lst) / len(avg_lst)
        return avg
    print(func(150000))
    print(func(160000))
    print(func(170000))
    print(func(150000))
    
    def func():
        avg_lst = []  # 自由变量
        def foo(price):
            avg_lst.append(price)
            avg = sum(avg_lst) / len(avg_lst)
            return avg
        return foo
    ret = func()
    print(ret(150000))
    print(ret(160000))
    print(ret(170000))
    print(ret(150000))
    
    判断是否为闭包:
    print(ret.__closure__)
    
    # 了解:
    print(ret.__code__.co_freevars)  # 获取的是自由变量
    print(ret.__code__.co_varnames)  # 获取的是局部变量
    
    

    3.其他

    python3:
    g = range(0,10)     # 可迭代对象
    g.__iter__()
    
    python2:
    range(0,10)        #获取的是一个列表
    xrange(0,10)       #获取的是一个可迭代对象
    
    验证是否为可迭代对象:
    g = range(0,10)
    g.__iter__()
    
    g = range(0,10)
    from collections import  Iterable,Iterator
    print(isinstance(g,Iterable))
    
  • 相关阅读:
    Cannot initialize Cluster. Please check your configuration for mapreduce.framework.name
    docker-compose 安装solr+ikanalyzer
    centos 安装Python3
    spring+springmvc+mybatis 开发JAVA单体应用
    职责链模式例子
    ssm(spring、springmvc、mybatis)框架整合
    PAT (Advanced Level) Practise
    PAT (Advanced Level) Practise
    PAT (Advanced Level) Practise
    PAT (Advanced Level) Practise
  • 原文地址:https://www.cnblogs.com/tutougold/p/11228602.html
Copyright © 2020-2023  润新知