zoukankan      html  css  js  c++  java
  • 内置函数

    Python中有一些提前定义好的函数供我们使用,截止至3.6.2版本,python一共为我们提供了68个内置函数

    下附链接为内置函数的思维导图,以供了解:

    https://www.processon.com/mindmap/5a4e0336e4b078cf1ee0392b

    为了便于学习了解,对这68个函数进行了归纳整理,将其分为6大类。

    • 作用域相关(2)
      • 基于字典的形式获取局部变量和全局变量
        • globals()——获取全局变量的字典
        • locals()——获取执行本方法所在命名空间内的局部变量的字典
    • 迭代器/生成器相关(3)
    • 反射相关(4)
    • 面向对象相关(9)
    • 基础数据类型相关(38)
      • 和数字相关
        • 数字——数据类型相关:bool,int,float,complex-复数
        • 数字——进制转换相关:bin-二进制0b,oct-八进制0o,hex-十六进制0x
        • 数字——数学运算:abs-绝对值,divmod-返回(除,余),min-最小值,max-最大值,sum-和,round-精确小数位,pow-幂运算
      • 和数据结构相关
        • 序列——列表和元组相关的:list和tuple
        • 序列——字符串相关的:str,format,bytes,bytearry,memoryview,ord,chr,ascii,repr
          ret = bytearray('alex',encoding='utf-8')
          print(id(ret))
          print(ret[0])
          ret[0] = 65
          print(ret)
          print(id(ret))
          
          #结果
          4316377304
          97
          bytearray(b'Alex')
          4316377304
          bytearray
          ret = memoryview(bytes('你好',encoding='utf-8'))
          print(len(ret))
          print(bytes(ret[:3]).decode('utf-8'))
          print(bytes(ret[3:]).decode('utf-8'))
          
          #结果:
          6
          你
          好
          memoryview
        • 序列:reversed,slice
          l = (1,2,23,213,5612,342,43)
          print(l)
          print(list(reversed(l)))
          
          #结果:
          (1, 2, 23, 213, 5612, 342, 43)
          [43, 342, 5612, 213, 23, 2, 1]
          
          l = (1,2,23,213,5612,342,43)
          sli = slice(1,5,2)
          print(l[sli])
          
          #结果:
          (2, 213)
          reversed、slice
      • 数据集合——字典和集合:dict,set,frozenset
      • 相关内置函数:len,sorted,enumerate,all,any,zip,filter,map
        • filter  :filter()函数接收一个函数 f 和一个list,这个函数 f 的作用是对每个元素进行判断,返回 True或 False,filter()根据判断结果自动过滤掉不符合条件的元素,返回由符合条件元素组成的新list。
          #删除偶数,保留奇数
          def is_odd(x):
              return x % 2 == 1
          ret = filter(is_odd, [1, 4, 6, 7, 9, 12, 17])
          for i in ret:
              print(i)
          #结果:
          1
          7
          9
          17
          #删除 None 或者空字符串:
          def is_not_empty(s):
              return s and len(s.strip()) > 0
          filter(is_not_empty, ['test', None, '', 'str', '  ', 'END'])
          # 注意: s.strip(rm) 删除 s 字符串中开头、结尾处的 rm 序列的字符。
          # 当rm为空时,默认删除空白符(包括'
          ', '
          ', '	', ' '),如下:
          a = ' 123'
          a.strip()
          #结果:
          '123'
          a = '		123
          '
          a.strip()
          #结果:
          '123'
          #请利用filter()过滤出1~100中平方根是整数的数
          import math
          def is_sqr(x):
              return math.sqrt(x) % 1 == 0
          print filter(is_sqr, range(1, 101))
          #结果:
          [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
          filter
        • map  Python中的map函数应用于每一个可迭代的项,返回的是一个结果list。如果有其他的可迭代参数传进来,map函数则会把每一个参数都以相应的处理函数进行迭代处理。map()函数接收两个参数,一个是函数,一个是序列,map将传入的函数依次作用到序列的每个元素,并把结果作为新的list返回。
          #L = [1,2,3,4,5,6,7,8],我们要将f(x)=x^2作用于这个list上,那么我们可以使用map函数处理。
          L = [1,2,3,4,]
          def pow2(x):
              return x*x
          
          ret = map(pow2,L)
          for i in ret:
              print(i)
          #结果:
          1
          4
          9
          16
          map
        • sorted  对List、Dict进行排序,Python提供了两个方法
          • 方法1.用List的成员函数sort进行排序,在本地进行排序,不返回副本
          • 方法2.用built-in函数sorted进行排序(从2.4开始),返回副本,原始输入不变 
            --------------------------------sorted---------------------------------------
            sorted(iterable, key=None, reverse=False)
            Return a new list containing all items from the iterable in ascending order.
            
            A custom key function can be supplied to customise the sort order, and the
            reverse flag can be set to request the result in descending order.
            
            
            -----------------------------------------------------------------------------
            参数说明:
            iterable:是可迭代类型;
            key:传入一个函数名,函数的参数是可迭代类型中的每一项,根据函数的返回值大小排序;
            reverse:排序规则. reverse = True  降序 或者 reverse = False 升序,有默认值。
            返回值:有序列表
            sorted参数说明
            l1 = [1,3,5,-2,-4,-6]
            l2 = sorted(l1,key=abs)
            print(l1)   #[1, 3, 5, -2, -4, -6]
            print(l2)   #[1, -2, 3, -4, 5, -6]
            按照绝对值进行排序
            l = [[1,2],[3,4,5,6],(7,),'123']
            print(sorted(l,key=len))  #[(7,), [1, 2], '123', [3, 4, 5, 6]]
            按照每一个元素的长度排序    
    • 其他(12)
      • 字符串类型代码的执行
        • eval() 将字符串类型的代码执行并返回结果
        • exec()将自字符串类型的代码执行
          print(eval('1+2+3+4'))
          print(exec("1+2+3+4"))
          exec("print('hello,world')")
          
          #结果:
          10
          None
          hello,world
          code = '''
          import os 
          print(os.path.abspath('.'))
          '''
          code = '''
          print(123)
          a = 20
          print(a)
          '''
          a = 10
          exec(code,{'print':print},)
          print(a)
          
          #结果:
          123
          20
          10
          指定global参数
        • compile将字符串类型的代码进行编译,代码对象能够通过exec语句来执行或者eval()进行求值。
          • compile(source,filename,mode,flags,dont_inherit)
          • 参数说明:   

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

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

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

            #流程语句使用exec
            code1 = 'for i in range(0,10): print (i)'
            compile1 = compile(code1,'','exec')
            exec (compile1)
            
            #结果:
            0
            1
            2
            3
            4
            5
            6
            7
            8
            9
            
            #简单求值表达式用eval
            code2 = '1 + 2 + 3 + 4'
            compile2 = compile(code2,'','eval')
            eval(compile2)
            print(eval(compile2)) #只有要求打印才会输出结果到屏幕
            
            #结果:
            10
            
            >>> #交互语句用single
            >>> code3 = 'name = input("please input your name:")'
            >>> compile3 = compile(code3,'','single')
            >>> name #执行前name变量不存在
            Traceback (most recent call last):
              File "<pyshell#29>", line 1, in <module>
                name
            NameError: name 'name' is not defined
            >>> exec(compile3) #执行时显示交互命令,提示输入
            please input your name:'pythoner'
            >>> name #执行后name变量有值
            "'pythoner'"
            View Code
      • 输入输出相关
        • input() 输入
          s = input("请输入内容 : ")  #输入的内容赋值给s变量
          print(s)  #输入什么打印什么。输入的内容数据类型是str
        • print() 输出
          def print(self, *args, sep=' ', end='
          ', file=None): # known special case of print
              """
              print(value, ..., sep=' ', end='
          ', file=sys.stdout, flush=False)
              file:  默认是输出到屏幕,如果设置为文件句柄,输出到文件
              sep:   打印多个值之间的分隔符,默认为空格
              end:   每一次打印的结尾,默认为换行符
              flush: 立即把内容输出到流文件,不作缓存
              """
          print源码分析
          f = open('tmp_file','w')
          print(123,456,sep=',',file = f,flush=True)
          file关键字的说明
          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)
          #pass : 
           可以把光标移动到行首但不换行
          示例:打印进度条
      • 数据类型相关:
        • type(o) 返回变量o的数据类型
          l = []
          print(type(l)) 
          print(type(123))
          
          #既可以查看变量的数据类型也可直接查看值的数据类型
          
          <class 'list'>
          <class 'int'>
      • 内存相关:
        • id(o) o是参数,返回一个变量的内存地址

        • hash(o) o是参数,返回一个可hash变量的哈希值,不可hash的变量被hash之后会报错。

          t = (1,2,3)
          l = [1,2,3]
          print(hash(t))  #可hash   结果:2528502973977326415
          print(hash(l))  #会报错  TypeError: unhashable type: 'list'

          hash函数会根据一个内部的算法对当前可hash变量进行处理,返回一个int数字。

          *每一次执行程序,内容相同的变量hash值在这一次执行过程中不会发生改变。

      • 文件操作相关

        open()  打开一个文件,返回一个文件操作符(文件句柄)

        操作文件的模式有r,w,a,r+,w+,a+ 共6种,每一种方式都可以用二进制的形式操作(rb,wb,ab,rb+,wb+,ab+)

        可以用encoding指定编码.

      • 模块操作相关

        __import__导入一个模块

        import time #倒入time模块
        
        #__import__用法
        os = __import__('os')
        print(os.path.abspath('.'))
      • 帮助方法

        在控制台执行help()进入帮助模式。可以随意输入变量或者变量的类型。输入q退出

        或者直接执行help(o),o是参数,查看和变量o有关的操作。。。

      • 和调用相关

        callable(o),o是参数,看这个变量是不是可调用。

        如果o是一个函数名,就会返回True

        def func():pass
        print(callable(func))  #参数是函数名,可调用,返回True
        print(callable(123))   #参数是数字,不可调用,返回False
      • 查看参数所属类型的所有内置方法

        dir() 默认查看全局空间内的属性,也接受一个参数,查看这个参数内的方法或变量

        print(dir(list))  #查看列表的内置方法
        print(dir(int))  #查看整数的内置方法

     进阶之匿名函数

      匿名函数:为了解决那些功能很简单的需求而设计的一句话函数,格式如下:

      

    简单示例

    #这段代码转换为匿名函数如下
    def calc(n):
        return n**n
    print(calc(10))
    
     
    #匿名函数
    calc = lambda n:n**n
    print(calc(10))
    函数名 = lambda 参数 :返回值
    
    #参数可以有多个,用逗号隔开
    #匿名函数不管逻辑多复杂,只能写一行,且逻辑执行结束后的内容就是返回值
    #返回值和正常的函数一样可以是任意数据类型

    匿名函数既可以拥有函数名也可以真的将名字匿起来,以下为匿名函数在与其他功能函数合作时用法:

    l=[3,2,100,999,213,1111,31121,333]
    print(max(l)) #31121 取最大值
    
    dic={'k1':10,'k2':100,'k3':30}
    print(max(dic)) #k3 这里比较的是最大的key而不是value
    print(dic[max(dic,key=lambda k:dic[k])]) #100
    
    res = map(lambda x:x**2,[1,5,7,4,8])
    for i in res:
        print(i)
    # 输出
    # 1
    # 25
    # 49
    # 16
    # 64
    res = map(lambda x:x**2,[1,5,7,4,8])
    print(list(res))  #[1, 25, 49, 16, 64]  也可以转成列表形式进行输出
    print(list(res))  #  打印结果为空 []  因为res是一个生成器,只能取一次,当里面的值取完之后就没有了
    
    res = filter(lambda x:x>10,[5,8,11,9,15])
    for i in res:
        print(i)
    
    # 输出
    # 11
    # 15
    匿名函数和内置函数的简单搭配

    示例进阶版

    #现有两个元组(('a'),('b')),(('c'),('d')),请使用python中匿名函数生成列表[{'a':'c'},{'b':'d'}]
    
    #答案一
    test = lambda t1,t2 :[{i:j} for i,j in zip(t1,t2)]
    print(test(t1,t2))
    #答案二
    print(list(map(lambda t:{t[0]:t[1]},zip(t1,t2))))
    #还可以这样写
    print([{i:j} for i,j in zip(t1,t2)])
    
    #结果:
    [{'a': 'c'}, {'b': 'd'}]
    匿名与内置演练
    #1.下面程序的输出结果是:
    d = lambda p:p*2
    t = lambda p:p*3
    x = 2
    x = d(x)
    x = t(x)
    x = d(x)
    print x
    
    2.以下代码的输出是什么?请给出答案并解释。
    def multipliers():
        return [lambda x:i*x for i in range(4)]
    print([m(2) for m in multipliers()])
    请修改multipliers的定义来产生期望的结果[0,2,4,6]。
    d = lambda p:p*2 #拆分函数如下:
    # def d(p):
    #     return p*2
    t = lambda p:p*3 ##拆分函数如下:
    # def t(p):
    #     return p*3
    x = 2
    x = d(x) # x = d(2) = 2*2
    x = t(x) # x = t(2*2) = 2*2*3
    x = d(x) # x = d(2*2*3) = 2*2*3*2
    print(x) # 24
    
    
    def multipliers():
        return [lambda x:i*x for i in range(4)]
    print([m(2) for m in multipliers()])
    
    #结果:
    [6, 6, 6, 6]
    
    def multipliers():
        return (lambda x:i*x for i in range(4))
    print([m(2) for m in multipliers()])
    
    #结果:
    [0, 2, 4, 6]
    解析
  • 相关阅读:
    读取纯真IP数据库C++源代码
    Ubuntu 安装VMware tools 解决方法讨论
    VMware虚拟机磁盘压缩
    使用 TestLink 进行测试管理
    正则表达式30分钟入门教程(转)
    HDU 1325 Is It A Tree? POJ 1308 Is It A Tree? (并查集+入度,判断一个有向图是树)
    POJ 1703 Find them, Catch them (并查集)
    POJ 1182 食物链(并查集)
    POJ 1984 Navigation Nightmare (并查集)
    POJ 2236 Wireless Network (并查集)
  • 原文地址:https://www.cnblogs.com/shi-guang/p/8232734.html
Copyright © 2011-2022 走看看