• Eight-内置函数和匿名函数


    内置函数

    1、range

    下面这两种用法的结果是一致的

    print(range(100).__iter__())
    print(iter(range(100)))
    
    # <range_iterator object at 0x000001C62FCB8EF0>
    # <range_iterator object at 0x000001C62FCB8EF0>

    2、eval和exec

    由下例可以看出来eval和exec都可以将引号去掉,但是eval是有返回值的,exec没有返回值,只会输出None

    print(eval('1,2,3,4'))  # (1,2,3,4)
    print(eval('1+2-3+4'))  # 4
    print(exec('1+2-3+4'))  # None
    exec("print('1+2-3+4')")  # 1+2-3+4
    eval("print('1+2-3+4')")  # 1+2-3+4

    3、compile  

    将字符串类型的代码编译,代码对象能够通过exec语句来执行或者eval进行求值

    参数说明:   

    1. 参数source:字符串或者AST(Abstract Syntax Trees)对象,即需要动态执行的代码段  

    2. 参数 filename:代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。当传入了source参数时,filename参数传入空字符即可 

    3. 参数model:指定编译代码的种类,可以指定为 ‘exec’,’eval’,’single’。当source中包含流程语句时,model应指定为‘exec’;当source中只包含一个简单的求值表达式,model应指定为‘eval’;当source中包含了交互式命令语句,model应指定为'single'

    codel='for i in range(0,10):print(i)'
    compilel=compile(codel,'','exec')
    exec(compilel)
    
    # 0
    # 1
    # 2
    # 3
    # 4
    # 5
    # 6
    # 7
    # 8
    # 9
    

      

    #简单求值表达式用eval
    code1='1+2+3+4'
    compile=compile(code1,'','eval')
    print(eval(compile))
    # 10
    

      

    #交互语句用single
    code='name=input("please input your name:")'
    compile=compile(code,'','single')
    name
    # 运行结果
    # Traceback (most recent call last):
    #   File "C:/Pythonbc/课堂/内置函数.py", line 177, in <module>
    #     name
    # NameError: name 'name' is not defined
    

     

    code='name=input("please input your name:")'
    compile=compile(code,'','single')
    exec(compile)
    name
    # please input your name:alex

    4、iterator

    下面代码中的两个print的效果是一样的,都是调用生成器,并从其中取值

    iterator=iter(range(100))
    print(iterator.__next__())  # 0
    print(next(iterator))  # 1

    5、dir

    判断某个数据类型中有什么用法

    print(dir([]))
    # ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__',
     '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', 
    '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', 
    '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index',
     'insert', 'pop', 'remove', 'reverse', 'sort']
    View Code

    查看某数据类型的用法有3种:

      1、ctrl +鼠标左键单击:这是pycharm提供的方法

      2、help:会查看到所有的方法以及它的使用方法,但是不知道用法

      3、dir:查看到的只是方法名,这个方法适用于查看某方法是否在这个数据类型中

    6、import

      用法:import+模块名

    import time  # 时间
    import os  # 操作系统

    7、文件操作方法:open

      f=open('文件名','w',encoding='utf-8')

      打开模式:r、w、a、rb、wb、ab

      编码:utf-8/gbk

    8、buffering(缓存)

    9、hash(哈希)

    print(id(1))  # 1779414080
    print(id(2))  # 1779414080
    print(hash('hdhshd'))  # 7061084334364224280
    print(hash(123445))  # 123445
    print(hash((1,2,3,4)))  # 485696759010151909

    相同的内容的哈希结果是相同的

    可用于:1、数据的存储和查找;2、模块:hashlib

    判断一个数据类型是否可以hash,在一个程序执行过程中,对同一个值的hash的结果总是不变的;多次执行,对同一个值的hash结果可能改变。

    10、 print

      def print(self,*args,sep=‘ ’,end=' ',file=None)

    print(1,2,3,4,sep='/')  # 1/2/3/4
    print(1,2,3,4,sep='*')  # 1*2*3*4
    print(1,2,sep=',')  # 1,2

    其中sep在print中默认为以空格来分隔,且在结尾的时候是有一个end的默认参数,传的是 (换行符)

    print('abc
    ')
    print(2)
    # abc
    # 
    # 2 

    在print中file的默认值是None,可以自己设定一个文件,如下所示,文件中存入了abc

    f=open('a','w')
    print('abc
    ',file=f)   # abc被写入了文件中
    print(2)
    
    # 2

     进度条:其中 :不论运行了多少,都要将光标移到最前面,相当于seek(0)

    import time
    for i in range(0,101,2):
        time.sleep(0.1)
        char_num=i//2
        per_str = '
    %s%%:%s
    ' % (i, '*' * char_num) if i == 100 
                                  else '
    %s%%:%s' % (i, '*' * char_num)
        print(per_str,end='',flush=True)
    
    # 100%:**************************************************

    11、id:可以很快的找到某数据的存储地址

    print(id(1))  # 1888793664
    print(id(2))  # 1888793696

    12、 bool:只有True和False两个值;可以与int、str之间之间相互转换

    print(bool(''))  # False
    print(bool(0))  # False
    print(bool('a'))  # True
    print(bool(1))  # True 

    13、int:整型,可以与bool、str之间相互转换

    print(int(False))  # 0
    print(int(True))  # 1

    14、float:浮点型(可以理解为带小数点的数据)

    15、abs:计算绝对值

    print(abs(-24))  # 24

    16、divmod:计算,并且返回除数和余数

    print(divmod(35,4))   # (8,3)

    17、round:保留小数点的位数,可自定义 round(number,ndigits)

    print(round(3.1415926,3))  # 3.142 

    18、pow:幂运算

    print(pow(2,2))  # 4
    print(pow(2,2,2))  # 0
    print(pow(2,2,3))  # 1

    19、sum:

    计算数据的和

    print(sum([1,2,3,4,5,6]))  # 21

    20、min:比较数据的大小,返回最小值min(iterable,key,default)

    t=(-25,31,6,8)
    print(min(t))  # -25
    print(min(t,key=abs))  # 6
    print(min((),default=0))  # 0

    21、max:比较数据的大小,返回最大值max(iterable,key,default)

    t=(-25,31,6,8)
    print(max(t))  # 31
    print(max(t,key=abs))  # 31
    print(max((),default=0))  # 0 

    22、list:列表,以['列表中的内容']的形式表现出来,可以对列表内的元素进行增删改查,是可迭代对象,可强制转换成元组tuple(list)

    23、tuple:元组,以('元组中的内容')的形式表现出来,是可迭代对象,但元组内的元素不可变,可强制转换成列表list(tuple)

    24、reversed:返回的是迭代器,不改变原来的列表,在内存中额外开辟一个新的空间来存储新的序列迭代器,这样比较占内存,但是并不是在原来的列表上进行修改,这样保留了原来的列表中的内容。

    25、reverse:返回的值是None,是在原列表的基础上对列表进行修改的,虽然节省了内存空间,但是改变了原列表中的内容。

    26、bytes

    print(bytes('ab',encoding='utf-8')) # b'ab'

    26、ascii

    只要是ascii码中的内容就打印出来,如果不是就转换成u

    print(ascii(2))  # 2
    print(ascii('a'))  # 'a'
    print(ascii('哇哈哈'))  # 'u54c7u54c8u54c8'

    27、repr:用于%r格式化输出

    print(repr(2))  # 2
    print(repr('wahaha'))  # 'wahaha'
    print(repr(2+4))  # 6
    print(repr('q'+'a'))  # 'qa'

    28、locals:局部变量,作用域根据locals的使用地方来确定其使用范围。

    29、globals:全局变量,可在函数中使用globals来改变函数的使用范围,但最好不要用,在使用globals改变变量的值的同时,全局变量中的变量值也会同时发生改变。

    30、next:迭代器包含有用法。

    31、iter:可迭代对象同时拥有next和iter用法。

    32、callable:判断是否为可迭代对象

    def func():pass
    a=1
    print(callable(a))  # False
    print(callable(print))  # True
    print(callable(func))  # True

    匿名函数

    为了解决那些功能很简单的需求而设计的一句话函数

    #函数
    def calc(n):
        return n**n
    print(calc(10))
     
    #换成匿名函数
    calc = lambda n:n**n
    print(calc(10))
    

    匿名函数格式说明

    函数名 = lambda 参数 :返回值
    
    #参数可以有多个,用逗号隔开
    #匿名函数不管逻辑多复杂,只能写一行,且逻辑执行结束后的内容就是返回值
    #返回值和正常的函数一样可以是任意数据类型
    

    匿名函数并不是真的不能有名字,匿名函数的调用和正常的调用没有什么区别,就是函数(参数)就可以了 

    def add(x,y):
        return x+y
    
    
    add = lambda x,y:x+y
    print(add(2,3))
    

    除此之外,匿名函数还可以和其他函数合作

    l=[3,2,100,999,213,1111,31121,333]
    print(max(l))
    
    dic={'k1':10,'k2':100,'k3':30}
    
    print(max(dic))
    print(dic[max(dic,key=lambda k:dic[k])])
    

     

    res = map(lambda x:x**2,[1,5,7,4,8])
    for i in res:
        print(i)
    
    输出
    1
    25
    49
    16
    64
    

      

    res = filter(lambda x:x>10,[5,8,11,9,15])
    for i in res:
        print(i)
    
    输出
    11
    15
    

      

  • 相关阅读:
    Xcode的控制台调试命令
    android 分辨率自适应
    android 分辨率自适应
    android屏幕适配
    android屏幕适配
    最新版本的ADT使用问题
    最新版本的ADT使用问题
    UVa 1639 Candy (数学期望+组合数学+高精度存储)
    UVa 12230 && HDU 3232 Crossing Rivers (数学期望水题)
    HDU 1087 Super Jumping! Jumping! Jumping! (DP+LIS)
  • 原文地址:https://www.cnblogs.com/gumo/p/7827186.html
Copyright © 2020-2023  润新知