zoukankan      html  css  js  c++  java
  • 第六篇:python基础_6 内置函数与常用模块(一)

    本篇内容

    1. 内置函数
    2. 匿名函数
    3. re模块
    4. time模块
    5. random模块
    6. os模块
    7. sys模块
    8. json与pickle模块
    9. shelve模块

    一、 内置函数

    1.定义

    内置函数又被称为工厂函数。

    2.常用的内置函数

    (1)abs()

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    print(abs(-1))
    

     (2)all()

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    print(all([1,2,'a',None]))
    print(all([]))
    

     (3)any()

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    print(any([]))
    print(any([' ',None,False]))
    print(any(['',None,False]))
    print(any(['',None,False,1]))
    

     (4)bin(),oct(),hex()

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    print(bin(10))
    print(oct(10))
    print(hex(10))
    

     (5)bytes()

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    #unicode----encode----->bytes
    print('hello'.encode('utf-8'))
    print(bytes('hello',encoding='utf-8'))
    

     (6)callable()

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    print(callable(bytes))
    print(callable(abs))
    

     (7)chr(),ord()

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    print(chr(65))
    print(chr(90))
    print(ord('#'))
    

     (8)int()

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    x=1
    print(type(x))
    x=int(2)
    print(type(x))
    

     complex()、float()、str()、list()、tuple()、dict()与int()同理

    (9)set(),可变集合

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    s={1,2,3,4}
    print(type(s))
    

     (10)frozenset(),不可变集合

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    s1=frozenset({1,2,3,4})
    print(type(s1))
    

     (11)dir()

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    import sys
    #sys.path
    # sys.argv
    print(dir(sys))
    

     (12)divmod()

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    print(divmod(10,3))
    print(divmod(102,20))
    

     (13)enumerate()

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    l=['a','b','c']
    res=enumerate(l)
    for i in res:
        print(i)
    for index,item in enumerate(l):
        print(index,item)
    

     (14)globals(),locals(),查看全局作用域和局部作用域

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    print(globals())
    

     (15)hash()

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    print(hash('abcdefg123'))
    print(hash('abcdefg123'))
    

     (16)help()

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    def func():
        '''
        test function
        :return:
        '''
        pass
    
    print(help(func))
    

     (17)id(),是python解释器实现的功能,只是反映了变量在内存的地址,但并不是真实的内存地址

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    x=1
    print(id(x))
    def func():
        pass
    print(id(func))
    print(func)
    

    (18)isinstance()

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    x=1
    print(type(x) is int)
    print(isinstance(x,int))
    

     (19)max(),min()

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    print(max([1,2,3,10]))
    print(max(['a','b']))
    print(min([1,2,3,10]))
    

     (20)pow()

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    print(pow(3,2,2)) #3**2%2
    

     (21)repr(),str()

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    print(type(str(1)))
    print(type(repr(1)))
    

     (22)reversed()

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    l=[1,'a',2,'c']
    print(list(reversed(l)))
    print(l)
    

     (23)slice()

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    l=[1,2,3,4,5,6]
    print(l[0:4:2])
    
    s=slice(0,4,2)
    print(l[s])
    

     (24)sorted()

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    l=[1,10,4,3,-1]
    print(sorted(l,reverse=True))
    

     (25)sum()

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    print(sum([1, 2,3]))
    print(sum(i for i in range(10)))
    

     (26)vars()

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    import m1
    print(vars(m1) == m1.__dict__)
    

     (27)zip()

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    s='helloss'
    l=[1,2,3,4,5]
    print(list(zip(s,l)))
    

     (28)__import__()

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    import sys
    
    m_name=input('module>>: ')
    if m_name == 'sys':
        m=__import__(m_name)
        print(m)
        print(m.path)
    
    sys=__import__('sys')
    print(sys)
    

     (29)round()

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    print(round(3.565,2))
    print(round(3.555,2))
    

    二、 匿名函数

    1.定义

     匿名函数:

    (1)没有名字。

    (2)函数体自带return。

    匿名函数的应用场景:
    应用于一次性的场景,临时使用。

    2.使用

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    def func(x,y,z=1):
        return x+y+z
    
    print(func)
    print(func(1,2,3))
    
    print(lambda x,y,z=1:x+y+z)
    f=lambda x,y,z=1:x+y+z
    print(f)
    print(f(1,2,3))
    

    三、 re模块

    (1)

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    import re
    
    print(re.findall('w','hello_ | yanglei 123'))
    print(re.findall('W','hello_ | yanglei 123'))
    print(re.findall('s','hello_ | yanglei 123 
     	'))
    print(re.findall('S','hello_ | yanglei 123 
     	'))
    print(re.findall('d','hello_ | yanglei 123 
     	'))
    print(re.findall('D','hello_ | yanglei 123 
     	'))
    print(re.findall('h','hello_ | hello h yanglei 123 
     	'))
    print(re.findall('Ahe','hello_ | hello h yanglei 123 
     	'))
    print(re.findall('^he','hello_ | hello h yanglei 123 
     	'))
    print(re.findall('123','hello_ | hello h yanglei 123 
     	123'))
    print(re.findall('123$','hello_ | hello h yanglei 123 
     	123'))
    print(re.findall('
    ','hello_ | hello h yanglei 123 
     	123'))
    print(re.findall('	','hello_ | hello h yanglei 123 
     	123'))
    

     (2). [] [^]

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    import re
    
    #.本身代表任意一个字符
    print(re.findall('a.c','a a1c a*c a2c abc a c aaaaaac aacc'))
    
    #[]内部可以有多个字符,但是本身只配多个字符中的一个
    print(re.findall('a[0-9][0-9]c','a a12c a1c a*c a2c a c a
    c',re.S))
    print(re.findall('a[a-zA-Z]c','aac abc aAc a12c a1c a*c a2c a c a
    c',re.S))
    print(re.findall('a[^a-zA-Z]c','aac abc aAc a12c a1c a*c a2c a c a
    c',re.S))
    print(re.findall('a[+/*-]c','a-c a+c a/c aac abc aAc a12c a1c a*c a2c a c a
    c',re.S))
    

     (3):转义

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    import re
    
    print(re.findall(r'a\c','ac abc'))
    

     (4)? * + {}:左边有几个字符,如果有的话,贪婪匹配

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    import re
    
    #?左边那一个字符有0个或者1个
    print(re.findall('ab?','aab a ab aaaa'))
    
    #*左边那一个字符有0个或者无穷个
    print(re.findall('ab*','a ab abb abbb abbbb bbbbbb'))
    print(re.findall('ab{0,}','a ab abb abbb abbbb bbbbbb'))
    
    #+左边那一个字符有1个或者无穷个
    print(re.findall('ab+','a ab abb abbb abbbb bbbbbb'))
    print(re.findall('ab{1,}','a ab abb abbb abbbb bbbbbb'))
    
    #{n,m}左边的字符有n-m次
    print(re.findall('ab{3}','a ab abb abbb abbbb bbbbbb'))
    print(re.findall('ab{2,3}','a ab abb abbb abbbb bbbbbb'))
    

     (5).* .*?

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    import re
    
    #.*贪婪匹配
    print(re.findall('a.*c','a123c456c'))
    
    #.*?非贪婪匹配
    print(re.findall('a.*?c','a123c456c'))
    

     (6)|

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    import re
    
    print(re.findall('company|companies','Too many companies have gone bankrupt, and the next one is my company'))
    print(re.findall('compan|companies','Too many companies have gone bankrupt, and the next one is my company'))
    

     (7)():分组

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    import re
    
    print(re.findall('ab+','abababab123'))
    print(re.findall('ab+123','abababab123'))
    
    print(re.findall('ab','abababab123'))
    print(re.findall('(ab)','abababab123'))
    print(re.findall('(a)b','abababab123'))
    print(re.findall('a(b)','abababab123'))
    print(re.findall('(ab)+','abababab123'))
    print(re.findall('(?:ab)+','abababab123'))
    
    print(re.findall('(ab)+123','abababab123'))
    print(re.findall('(?:ab)+123','abababab123'))
    print(re.findall('(ab)+(123)','abababab123'))
    
    print(re.findall('compan(y|ies)','Too many companies have gone bankrupt, and the next one is my company'))
    print(re.findall('compan(?:y|ies)','Too many companies have gone bankrupt, and the next one is my company'))
    

     (8)re的其他方法

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    import re
    
    print(re.findall('ab','abababab123'))
    print(re.search('ab','abababab123').group())
    print(re.search('ab','12aasssdddssssssss3'))
    print(re.search('ab','12aasssdddsssssssab3sssssss').group())
    print(re.search('ab','123ab456'))
    
    print(re.match('ab','123ab456'))
    
    print(re.split('b','abcde'))
    print(re.split('[ab]','abcde'))
    
    print(re.sub('xiaolan','xiaohong','xiaolan make love xiaolan xiaolan',1))
    print(re.subn('xiaolan','xiaohong','xiaolan make love xiaolan xiaolan',1))
    print(re.sub('(w+)(W+)(w+)(W+)(w+)',r'52341','Toms make love'))
    print(re.sub('(w+)( .* )(w+)',r'321','Toms make love'))
    
    obj=re.compile('d{2}')
    print(obj.search('abc123eeee').group())
    print(obj.findall('abc123eeee'))
    

    四、time模块

    模块方法

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    import time
    
    print(time.time())
    print(time.strftime('%Y-%m-%d %X'))
    
    print(time.localtime())
    print(time.gmtime()) #UTC
    print(time.localtime().tm_mon)
    
    print(time.localtime(123123123))
    print(time.gmtime(123123123))
    
    print(time.mktime(time.localtime()))
    
    print(time.strftime('%Y',time.gmtime()))
    
    '2017-03-01'
    print(time.strptime('2017-03-01','%Y-%m-%d'))
    
    print(time.ctime(12312312))
    print(time.asctime(time.gmtime()))
    

    五、random模块

    1.模块方法

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    import random
    print(random.sample([1,'23',[4,5]],2))
    
    print(random.uniform(1,3))
    
    item=[1,3,5,7,9]
    random.shuffle(item)
    print(item)
    

    2. 生成秘钥应用

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    import random
    def make_code(n):
        res=''
        for i in range(n):
            s1=str(random.randint(0,9))
            s2=chr(random.randint(65,90))
            res+=random.choice([s1,s2])
        return res
    print(make_code(10))
    

    六、os模块

    模块方法

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    import os
    
    print(os.listdir('.'))
    
    print(os.stat('m1.py').st_size)
    
    print(os.sep)
    print(os.linesep)
    print(os.pathsep)
    
    print([os.sep,os.linesep,os.pathsep])
    
    res=os.system('dir .')
    print('====?>',res)
    
    print(os.path.dirname(r'C:acda.txt'))
    print(os.path.basename(r'C:acda.txt'))
    print(os.path.split(r'C:acda.txt'))
    
    print(os.stat('m1.py').st_atime)
    print(os.stat('m1.py').st_size)
    print(os.path.getsize('m1.py'))
    
    print(os.path.join('C:\','a','b','c','d.txt'))
    print(os.path.join('C:\','a','b','D:\','c','d.txt'))
    
    print(os.path.normcase('c:/wiNdows\system32\')  )
    
    print(os.path.normpath('c://wIndows\System32\../Temp/')  )
    
    a='/Users/jieli/test1/\a1/\\aa.py/../..'
    print(os.path.normpath(a))
    
    
    print(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    
    BASE_DIR=os.path.normpath(os.path.join(
        os.path.abspath(__file__),
        '..',
        '..'
    )
    )
    print(BASE_DIR)
    

    七、sys模块

    模拟进度条应用

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    import sys,time
    
    
    def progress(percent,width=50): #51
        if percent >= 100:
            # print('
    [%s] 100%%' %(width*'#'))
            percent=100
        show_str=('[%%-%ds]' %width) %(int(width*percent/100)*'#')
        print('
    %s %d%%' %(show_str,percent),file=sys.stdout,flush=True,end='')
    #
    total_size=1025121
    recv_size=0
    
    while recv_size < total_size:
        time.sleep(0.01) #模拟下载的网络延迟
        recv_size+=1024
        recv_per=int(100*recv_size/total_size)
        progress(recv_per,width=10)
    

    八、json与pickle模块

    (1)json

    应用平台广泛

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    import json
    dic={'name':'yanglei','age':23}
    
    print(type(json.dumps(dic)))
    
    with open('a.json','w') as f:
        f.write(json.dumps(dic))
    
    with open('a.json','r') as f:
        data=f.read()
        dic=json.loads(data)
        print(dic['name'])
    
    dic={'name':'yanglei','age':23}
    json.dump(dic,open('b.json','w'))
    print(json.load(open('b.json','r'))['name'])
    
    with open('c.json','r') as f:
        data=f.read()
        #[null,true,false,1]
        eval(data)
    

     (2)pickle

    只对python有效

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    import pickle
    
    dic={'name':'yanglei','age':23}
    
    print(pickle.dumps(dic))
    with open('d.pkl','wb') as f:
        f.write(pickle.dumps(dic))
    
    with open('d.pkl','rb') as f:
        dic=pickle.loads(f.read())
        print(dic['name'])
    
    dic={'name':'yanglei','age':23}
    pickle.dump(dic,open('e.pkl','wb'))
    
    print(pickle.load(open('e.pkl','rb'))['name'])
    
    def func():
        print('from func')
    
    import json
    print(json.dumps(func))
    
    import pickle
    print(pickle.dumps(func))
    pickle.dump(func,open('func.pkl','wb'))
    

    九、shelve模块

     模块方法

    #!/usr/binl/env python
    #encoding: utf-8
    #author: YangLei
    
    import shelve
    
    f=shelve.open(r'sheve.shl')
    
    f['yanglei']={'age':23,'pwd':'123456'}
    f['xiaolan']={'age':18,'pwd':'123456'}
    f.close()
    
    obj=shelve.open(r'sheve.shl')
    
    print(obj['yanglei'])
    print(obj['xiaolan'])
    
    obj.close()
    
    for i in obj:
        print(i,obj[i])
    
  • 相关阅读:
    Oracle调优总结--(经典实践 重要)
    ORACLE索引介绍和使用
    ORACLE索引介绍和使用
    oracle update 改为 merge
    oracle update 改为 merge
    在 Eclipse 下利用 gradle 构建系统
    在 Eclipse 下利用 gradle 构建系统
    关于SQL查询效率,100w数据,查询只要1秒
    关于SQL查询效率,100w数据,查询只要1秒
    Add Binary
  • 原文地址:https://www.cnblogs.com/00doudou00/p/7323556.html
Copyright © 2011-2022 走看看