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

    区域函数
    locals() #函数会以字典的类型返回当前位置的全部局部变量
    globals() #函数以字典的类型返回全部全局变量
    字符串执行函数
    eval()#执行字符串类型的代码,并返回最终结果。
    print(eval('2+6')) 8
    exec() #执行字符串类型的代码。
    s = '''
    for i in [1,2,3]:
    print(i)
    '''
    exec(s)
    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'。
    '''
    >>> #流程语句使用exec
    >>> code1 = 'for i in range(0,10): print (i)'
    >>> compile1 = compile(code1,'','exec')
    >>> exec (compile1)
    
    
    >>> #简单求值表达式用eval
    >>> code2 = '1 + 2 + 3 + 4'
    >>> compile2 = compile(code2,'','eval')
    >>> eval(compile2)
    
    
    >>> #交互语句用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'"
    有返回值的字符串形式的代码用eval,没有返回值的字符串形式的代码用exec,一般不用compile

    1.2.2 输入输出相关 input,print

      input:函数接受一个标准输入数据,返回为 string 类型。

      print:打印输出。

    1.2.3内存相关 hash id

      hash:获取一个对象(可哈希对象:int,str,Bool,tuple)的哈希值。

    1.2.3内存相关 hash id

      hash:获取一个对象(可哈希对象:int,str,Bool,tuple)的哈希值。

    id:用于获取对象的内存地址。

    1.2.3文件操作相关

      open:函数用于打开一个文件,创建一个 file 对象,相关的方法才可以调用它进行读写。

    1.2.4模块相关__import__ 

      __import__:函数用于动态加载类和函数 。

    1.2.5帮助

      help:函数用于查看函数或模块用途的详细说明。

    1.2.6调用相关

      callable:函数用于检查一个对象是否是可调用的。如果返回True,object仍然可能调用失败;但如果返回False,调用对象ojbect绝对不会成功。

    dir:函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。如果参数包含方法__dir__(),该方法将被调用。如果参数不包含__dir__(),该方法将最大限度地收集参数信息。

    range:函数可创建一个整数对象,一般用在 for 循环中。

    next:内部实际使用了__next__方法,返回迭代器的下一个项目。

    # 首先获得Iterator对象:
    it = iter([1, 2, 3, 4, 5])
    # 循环:
    while True:
      try:

        # 获得下一个值:
        x = next(it)
        print(x)
        except StopIteration:# 遇到StopIteration就退出循环
        break

     iter:函数用来生成迭代器(讲一个可迭代对象,生成迭代器)。

    复制代码
    from collections import Iterable
    from collections import Iterator
    l = [1,2,3]
    print(isinstance(l,Iterable))  # True
    print(isinstance(l,Iterator))  # False
    
    l1 = iter(l)
    print(isinstance(l1,Iterable))  # True
    print(isinstance(l1,Iterator))  # True
    from collections import Iterable
    from collections import Iterator
    l = [1,2,3]
    print(isinstance(l,Iterable))  # True
    print(isinstance(l,Iterator))  # False
    
    l1 = iter(l)
    print(isinstance(l1,Iterable))  # True
    print(isinstance(l1,Iterator))  # True

    # 1.4 基础数据类型相关
    # 1.4.1数字相关(14)
    #   数据类型(4):
    #     **bool :用于将给定参数转换为布尔类型,如果没有参数,返回 False。
    # print(bool(''))
    #     **int:函数用于将一个字符串或数字转换为整型。
    # print(int('111'))
    # print(int(12.73)) # 浮点型 转化成整数(取整)
    # print(int('12.73')) # 报错
    # print(int('0100',base=2)) # 将2进制的 0100 转化成十进制。结果为 4
    # **float:函数用于将整数和字符串转换成浮点数。
    # print(1.22,type(1.22))
    #  *complex:函数用于创建一个值为 real + imag * j 的复数或者转化一个字符串或数为复数。
    # 如果第一个参数为字符串,则不需要指定第二个参数。。
    # print(complex(1,2))
    # *bin:将十进制转换成二进制并返回。
    # print(bin(3)) # 0b11
    # *oct:将十进制转化成八进制字符串并返回。
    # print(oct(9)) # 0o11
    # print(oct(10)) # 0o11
    # *hex:将十进制转化成十六进制字符串并返回。
    # print(hex(10)) # 0xa
    # print(hex(15)) # 0xf
    # print(hex(17)) # 0x11

    # 数学运算(7):
    #  abs:函数返回数字的绝对值。
    # print(abs(-5)) # 5
    # **divmod:计算除数与被除数的结果,返回一个包含商和余数的元组(a // b, a % b)。
    # print(divmod(7,3))
    # print(divmod(103,8))
    # * round:保留浮点数的小数位数,默认保留整数。
    # print(round(2.3287654)) # 默认保留整数
    # print(round(2.3987654, 2)) #
    # *pow:求x**y次幂。(三个参数为x**y的结果对z取余)
    # print(pow(3,3)) # pow(x,y) x ** y
    # print(pow(3,3,5)) # pow(x,y) x ** y
    # *** sum:对可迭代对象进行求和计算(可设置初始值)。
    # l1 = [1, 2, 3, 55, 77]
    # print(sum(l1))
    # print(sum(l1,100)) # 设置初始值

    # *** min:返回可迭代对象的最小值(可加key,key为函数名,通过函数的规则,返回最小值)。
    l1 = [1, 2, 3, 55, 77]
    l2 = [-1, -2, 3, 55, -77]
    # print(min(l1))
    # print(min(l2,key=abs))
    # *** max:返回可迭代对象的最大值(可加key,key为函数名,通过函数的规则,返回最大值)。
    # print(max(l1))
    # print(max(l2,key=abs))
    # dic = {'a': 3,'b': 2,'c': 1}
    # def func(x): return dic[x]
    # print(min(dic,key=func))
    # print(max(dic,key=func))
    # lis = [[1517991992.94, 100], [1517992000.94, 200], [1517992014.94, 300], [1517992744.94, 350], [1517992800.94, 280]]
    # def func1(x): return x[1]
    # print(max(lis,key=func1))

    # **list:将一个可迭代对象转化成列表(如果是字典,默认将key作为列表的元素)。
    # l1 = [1,2,3]
    # l2 = list([1,2,3]) #创建列表
    # l3 = list((1,2,3))
    # print(l3)
    # **tuple:将一个可迭代对象转化成元祖(如果是字典,默认将key作为元祖的元素)。
    #
    # View Code
    #   相关内置函数(2)
    # *** reversed:将一个序列翻转,并返回此翻转序列的迭代器。
    # l1 = [22, 33, 55, 11]
    # print(reversed(l1))
    # for i in reversed(l1):
    # print(i)
    # ** slice:构造一个切片对象,用于列表的切片。
    # l1 = [1, 2, 3, 55, 77]
    # l2 = [-1, -2, 3, 55, -77, 88]
    # print(l1[1:4])
    # print(l2[1:4])
    # rule = slice(1,6,2)
    # print(l1[rule])
    # print(l2[rule])
    # format:与具体数据相关,用于计算各种小数,精算等。
    # print(format('test', '<20'))
    # print(format('test', '>20'))
    # print(format('test', '^20'))
    # bytes:用于不同编码之间的转化。 将unicode ---> bytes
    # unicode ---> utf-8
    # s1 = 'alex'
    # b1 = s1.encode('utf-8')
    # b1 = bytes(s1,encoding='utf-8')
    # print(b1)/
    # print(b1)
    # s2 = b1.decode('utf-8')
    # print(s2)
    # s1 = '中国'
    # b1 = s1.encode('utf-8')
    # b2 = b1.decode('utf-8').encode('gbk')
    # print(b2)

    #  *bytearry:返回一个新字节数组。这个数组里的元素是可变的,并且每个元素的值范围: 0 <= x < 256。
    # ret = bytearray('alex', encoding='utf-8') # [97,104,101,109]
    # print(id(ret))
    # # print(ret)
    # print(ret[0])
    # ret[0] = 65
    # print(ret) # [65,104,101,109]
    # print(id(ret))
    #  *memoryview
    # ret = memoryview(bytes('你好',encoding='utf-8')) # [xe4,xbd,xa0,xe5,xa5,xbd]
    # # print(len(ret)) # 6
    # print(ret)
    # print(bytes(ret[:3]).decode('utf-8'))
    # print(bytes(ret[3:]).decode('utf-8'))
    # *ord: 输入字符找该字符编码的位置 unicode的编码
    # print(ord('a'))
    # print(ord('我'))
    # *chr: 输入位置数字找出其对应的字符 unicode
    # print(chr(97))
    # *ascii: 是ascii码中的返回该值,不是就返回 / u...
    # print(ascii('a'))
    # print(ascii('中国')) # 'u4e2du56fd'

    # ** repr: 返回一个对象的string形式(原形毕露)。
    # print(repr('中国'))
    # print(repr('{"name": "alex"}'))
    # s1 = '我是%s人' % ('中国')
    # s2 = '我是%r人' % ('中国')
    # print(s1)
    # print(s2)
    #   数据集合(3)
    #
    #     dict:创建一个字典。
    #
    #     set:创建一个集合。
    #
    #     frozenset:返回一个冻结的集合,冻结后集合不能再添加或删除任何元素。
    #
    #   相关内置函数(8)
    #
    # *** len: 返回一个对象中元素的个数。

    # *** sorted:对所有可迭代的对象进行排序操作。
    # l1 = [1, 4, 5, 77, 2, 3,]
    # print(sorted(l1))
    # L = [('a', 4), ('c', 3), ('d', 1),('b', 2), ]
    # def func2(x):
    # return x[1]
    # l2 = sorted(L,key=func2)
    # print(l2)

    #  ***enumerate: 枚举,返回一个枚举对象。
    #  **all:可迭代对象中,全都是True才是True
    #  **any:可迭代对象中,有一个True
    # l1 = ['asv', 1, True]
    # print(all(l1))
    # l2 = [True,"", 0, ()]
    # print(any(l2))
    # zip:函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的迭代器。
    # 如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同。
    # l1 = [1, 2, 3,]
    # l2 = ['a','b','c',5]
    # l3 = ('*','**',(1,2,3), 2, 4)
    # print(zip(l1,l2,l3)) 可以视为:[(1, 'a', '*'),(2, 'b', '**'),(3, 'c', (1, 2, 3))]
    # for i in zip(l1,l2,l3):
    # print(i)


    # *** filter:过滤·。
    # def func(x):
    # return x % 2 == 0
    # ret = filter(func,[1,2,3,4,5,6,7])
    # print(ret)
    # for i in ret:
    # print(i)
    # print((i for i in [1,2,3,4,5,6,7] if i % 2 == 0))
    # ***map:会根据提供的函数对指定序列做映射。
    # l1 = [1,2,3,4,5]
    # def func(x):
    # return x*x
    # ret = map(func,l1)
    # print(ret)
    # for i in ret:
    # print(i)

    # 匿名函数 一句话函数,一行表示
    # def func1(x,y): return x+y
    # func = lambda x,y : x+y
    # print(func1(1,2))
    # print(func(1,2))
    # lis = [[1517991992.94, 100], [1517992000.94, 200], [1517992014.94, 300], [1517992744.94, 350], [1517992800.94, 280]]
    # # def func1(x): return x[1]
    # # func1 = lambda x:x[1]
    # print(max(lis,key=lambda x:x[1]))

    # dic={'k1':10,'k2':100,'k3':30}
    # print(dic[max(dic,key=lambda x: dic[x])])




  • 相关阅读:
    记事本:js简介
    python 类的魔法函数 内置函数 类方法 静态方法 抽象类
    python 类
    python 列表 元组 字典 集合
    python:函数和循环判断
    记事本:盒模型
    第5章学习小结
    倍增法求LCA(最近公共最先)
    L
    第4章学习小结
  • 原文地址:https://www.cnblogs.com/kangxi/p/9210884.html
Copyright © 2011-2022 走看看