• Day013--Python--内置函数一


    一.作用域相关(2)

      1. globals()  查看全局空间作用域中的内容. 函数会以字典的类型返回全部全局变量.

      2. locals()  查看当前空间作用域中的内容. 函数以字典的类型返回当前位置的全部局部变量.

      

    print(globals())
    
    def func():
        a = 10
        print(locals())
        return
    print(func())
    View Code

    二.迭代器/生成器相关(3)

      1. range()  生成数据

    1 for i in range(10):
    2     print(i)
    View Code

      2. iter() 获取迭代器,内部实际使用的是__iter__()方法来获取迭代器

      3. next() 迭代器向下执行一次,内部实际使用了__next__()方法返回迭代器的下一个项目  
    lst = ["吃饭", "昨天", "没睡觉","干什么去了?"]
    it = lst.__iter__() #获取迭代器
    print(it.__next__())
    print(next(it))
    View Code

     三.基础数据类型相关(38)

      (一).和数字相关(14)

        I.数据类型(4)

          1. bool()  将给定的数据转换成bool值,如果不给值,返回False

    print(bool([1, 3, 5]))
    print(bool(''))
    View Code

          2. int () 将给定的数据转换成int值.如果不给值,返回0.

          3. float()  将给定的数据转换成float值,也就是小数

          4. complex()  创建一个复数.第一个参数为实部,第二个参数为虚部.或者第一个参数直接用字符串来描述复数

        II.进制转换(3)

          1. bin()  将给的参数转换成二进制

          2. oct()  将给的参数转换成八进制

          3. hex()  将给的参数转换成十六进制

    a = 5
    print(bin(a))
    
    b = 8
    print(oct(b))
    
    c = 16
    print(hex(c))
    View Code

        III.数学运算(7)

          1. abs()  返回绝对值

          2. divmod()  返回商和余数

          3. round()   奇数四舍五入,偶数五舍六入

          4. pow(a,b)  求a的b次幂,如果有三个参数,则求完次幂后对第三个数取余

    print(abs(-1))   #取绝对值
    
    print(divmod(10, 3))  #返回商3,余数1
    
    print(round(4.5))  #偶数5舍6入
    
    print(round(5.5))  #奇数4舍5入
    
    print(pow(2, 3, 3))  #2**3 % 3
    View Code

          5. sum()  求和

          6. min()  求最大值

          7. max()  求最小值

    a = sum([1, 3, 5])  # 只能是可迭代对象 iterable
    print(a)
    
    b = min([1, 3, 63, 9, 3])
    print(b)
    
    c = max([2, 33, 43, 33, 20])
    
    print(c)
    View Code

      (二).和数据结构相关(24)

        I.序列(13)

          a.列表和元祖(2)

            1. list()  将一个可迭代对象转换成列表

            2. tuple()  将一个可迭代对象转换成元组

          b.相关内置函数(2)

            1. reversed()  将一个序列翻转

    lst = [1, 4, 6, 8]
    it = reversed(lst)
    print('__iter__' in dir(it))
    for i in range(len(lst)):
        print(next(it))
    View Code

            2. slice()  列表的切片

    st = "⼤家好, 我是麻花藤"
    s = slice(1, 5, 2)
    print(st[s])
    View Code

           c.字符串(9)

            1. str()  将数据转化成字符串

            2. format()  与具体数据相关,用于计算各种小数,精算等

    # 字符串
    print(format('test', '<20')) # 左对⻬
    print(format('test', '>20')) # 右对⻬
    print(format('test', '^20')) # 居中
    # 数值
    print(format(3, 'b')) # ⼆进制
    print(format(97, 'c')) # 转换成unicode字符
    print(format(11, 'd')) # ⼗进制
    print(format(11, 'o')) # ⼋进制
    print(format(11, 'x')) # ⼗六进制(⼩写字⺟)
    print(format(11, 'X')) # ⼗六进制(⼤写字⺟)
    print(format(11, 'n')) # 和d⼀样
    print(format(11)) # 和d⼀样
    # 浮点数
    print(format(123456789, 'e')) # 科学计数法. 默认保留6位⼩数
    print(format(123456789, '0.2e')) # 科学计数法. 保留2位⼩数(⼩写)
    print(format(123456789, '0.2E')) # 科学计数法. 保留2位⼩数(⼤写)
    print(format(1.23456789, 'f')) # ⼩数点计数法. 保留6位⼩数
    print(format(1.23456789, '0.2f')) # ⼩数点计数法. 保留2位⼩数
    print(format(1.23456789, '0.10f')) # ⼩数点计数法. 保留10位⼩数
    print(format(1.23456789e+10000, 'F')) # ⼩数点计数法.
    View Code

             3. bytes()  把字符串转化成bytes类型

    s = "你好"
    bs = s.encode("utf-8")
    print(bs)
    s1 = bs.decode("utf-8")
    print(s1)
    bs = bytes(s, encoding="utf-8") # 把字符串编码成UTF-8
    print(bs)
    View Code

             4. bytearry()  返回一个新字节数组.这个数组里的元素是可变的,并且每个元素的值的范围值(0, 256)

    ret = bytearray('alex',encoding='utf-8')
    print(ret[0])    #返回a的位置
    print(ret)  
    
    ret = bytearray('王重阳', encoding='utf-8')
    print(ret[0])   #在utf-8中,一个中文字符是3bytes,返回第一个byte,也就是1/3个中文的位置
    print(ret)
    for el in bytearray(b'xe7x8ex8bxe9x87x8dxe9x98xb3'):
        print(el)
    View Code

             5. memoryview()  查看bytes在内存中的情况

    s = memoryview("麻花藤".encode("utf-8"))
    print(s)  #返回内存地址
    View Code

            6. ord()  输入字符 找带字符编码的位置

            7. chr()  输入位置数字找出对应的字符

            8. ascii()  是ASCII码中的返回该值,不是就返回u...

    # 找到对应字符的编码位置
    print(ord('a'))
    print(ord(''))
    
    # 找到对应编码位置的字符
    print(chr(97))
    print(chr(20013))
    
    # 在ascii中就返回这个值. 如果不在就返回u...
    print(ascii('a'))
    print(ascii(''))
    View Code

            9. repr()  返回一个对象的string形式 

    # repr 就是原封不动的输出, 引号和转义字符都不起作⽤
    print(repr('⼤家好,
     	我叫周杰伦'))
    print('⼤家好我叫周杰伦')
    
    # %r 原封不动的写出来
    s = '天空
    依然阴霾'
    print('歌词:%r' % s)
    
    #%r是repr;%s是str;前者是被repr处理后的string对象,后者直接是string对象
    View Code

        II.数据集合(3)

          a.字典(1)

            dict()  创建一个字典

    a = dict()   #创建一个空字典
    d = dict(k1='aaa', k2='bbb')  #给字典添加键值对
    print(a, d)
    View Code

          b.集合(2)

            1. set()  创建一个集合

    set()  #创建一个集合
    print(set('hello'))  #将hello迭代着加入,且由于set不重复,所以只添加'h','e','l','o'四个元素
    print(set(['hello']))   #{'hello'}
    View Code

            2. frozenset()  创建一个冻结的集合.冻结的集合不能进行添加和删除操作.

    set1 = {'barry', 'wusir'}
    set2 = frozenset(set1)
    print(set2,type(set2))
    
    for el in set2:
        print(el)     
    #frozenset 不可变,可迭代,不能增删,里面仍然无序
    View Code

        III.相关内置函数(8)

          1. len()  返回一个对象中的元素个数

    lst = [1, 2, 3, '呵呵', [1, 2, 3]]
    print(len(lst))
    View Code

          2. sorted()  对可迭代对象进行排序操作

          3. enumerate()  获取集合的枚举对象

    lst = ["alex", "wusir", "taibai"]
    for index, el in enumerate(lst):
        print(str(index)+"==>"+el)
    View Code

          4. all()  可迭代对象中全部是True,结果才是True , 相当于and

          5. any()  可迭代对象中有一个是True,结果就是True ,相当于or

    print(all([1,2,True,0]))
    print(any([1,'',0]))
    View Code

          6. zip()  函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回有这些元组组成

             的列表.如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同. (木桶效应)

    lst1 = ["中国", "美国", "俄罗斯", "日本"]
    lst2 = ["北京", "华盛顿", "莫斯科"]
    lst3 = ["烤鸭", "炸鸡", "黄油+面包", "寿司"]
    
    a = zip(lst1, lst2, lst3) # 合并列表, 返回可迭代对象, 水桶效应
    print("__iter__" in dir(a))
    
    for el in a:
        print(el)
    View Code

          7. filter()  过滤

          8. map()  会根据提供的函数对指定序列做映射(lamda)

    四.其他(12)

      (一).字符串类型代码的执行(3)

        1. eval()  执行字符串类型的代码,并返回最终结果

    print(eval('2 + 3'))
    
    n = 1
    print(eval('n + 2'))
    
    def func():
        print('666')
    
    eval('func()')
    View Code

        2. exec()  执行字符串类型的代码(只执行,不返回结果)

    exec('a = 1 + 2 + 3')
    print(a)    #a处会出现下划线提示有误,但是可以运行,眼见不一定为实
    
    exec("""
    for i in range(10):
     print(i)
    """)
    
    exec("""
    def func():
     print("我是周杰伦")
    func()
    """)
    View Code

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

    '''
     参数说明:
     1. resource 要执⾏的代码, 动态代码⽚段
     2. ⽂件名, 代码存放的⽂件名, 当传⼊了第⼀个参数的时候, 这个参数给空就可以了
     3. 模式, 取值有3个,
     1. exec: ⼀般放⼀些流程语句的时候
     2. eval: resource只存放⼀个求值表达式.
     3. single: resource存放的代码有交互的时候. mode应为single
    '''
    
    code1 = 'for i in range(10): print(i)'
    # exec(code1)
    c1 = compile(code1, '', mode='exec')
    exec(c1)
    
    
    code2 = "1+2+3"
    c2 = compile(code2, "", mode="eval")
    a = eval(c2)
    print(a)
    
    
    code3 = "name = input('请输⼊你的名字:')"
    c3 = compile(code3, "", mode="single")
    exec(c3)
    print(name)
    
    #编译后可以执行多行代码
    code1 = '''
    for i in range(10): 
        print(1)
    print('hello world')
        
    def func():
        print('我是函数')
    func()
    '''
    c1 = compile(code1, '', 'exec')
    exec(c1)
    View Code

      (二).输入输出(2)

        1. input()   获取用户输入内容,获取到的是字符串

        2. print()  打印输出

      (三).内存相关(2)

        1. hash()   获取到对象的哈希值(int, str, bool, tuple)

        2. id()   获取到对象的内存地址

      (四).文件操作相关(1)

        open()   用于打开一个文件,创建一个文件句柄.

    f = open('文件路径', mode= '模式(默认是读r)', encoding= '编码')  #获得句柄
    
    content = f.readline()
    
    print(content)
    View Code

      (五).模块相关(1)

        __import__()   用于动态加载类和函数

      (六).帮助

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

      (七).调用相关(1)

        callable()   用于检查一个对象是否是可调用的,如果返回True,object有可能调用失败,但如果返回False,调用绝对不会成功

      (八).查看内置属性(1)

        dir()   查看对象的内置属性,方法.访问的是对象中的__dir__()方法 

    a = {'k1': 1, 2: '呵呵'}
    print('__iter__' in dir(a))
    View Code

    print(__name__ )   在本py文件中显示为 __main__

    如果在其他py文件中import 这个py文件,则在引入的py文件中,显示出被引入的py文件中print的__name__改变为路径+被引入文件名,

      

  • 相关阅读:
    Devrama Slider
    全栈开发必备的10款 Sublime Text 插件
    经典网页设计:使用颜色滤镜效果的20个网站
    Nibbler – 免费的网站测试和指标评分工具
    使用 HTML5 Canvas 绘制出惊艳的水滴效果
    Qt4 和 Qt5 模块的分类
    设计Qt风格的C++API
    Qt属性系统
    Qt实现艺术字效果
    Qt中容器类应该如何存储对象(最好使用对象指针类型,如:QList<TestObj*>,而不要使用 QList<TestObj> 这样的定义,建议采用 智能指针QSharedPointer)
  • 原文地址:https://www.cnblogs.com/surasun/p/9675811.html
Copyright © 2020-2023  润新知