zoukankan      html  css  js  c++  java
  • 常用模块

    collections模块

      在内置数据类型(dict、list、set、tuple)的基础上,collections模块还提供了几个额外的数据类型:Counter、deque、defaultdict、namedtuple和OrderedDict等。

    namedtuple具名元组:  生成可以使用名字来访问元素内容的tuple

    from collections import namedtuple
    point1 = namedtuple('坐标',['x','y','z'])  # 第二个参数可以传可迭代对象
    point2 = namedtuple('坐标','x,y,z')  #第二个对象可以传字符串,字符串之间以空格隔开
    p1 = point1(1,3,5)  # 元素的个数与namedtuple里的第二个参数的值数量一致
    p2 = point2(1,3,5)
    print(p1)  # 坐标(x=1, y=3, z=5)
    print(p2)  # 坐标(x=1, y=3, z=5)
    
    card = namedtuple('扑克牌','color numer')
    A = card('','A')
    print(A.color)  # ♥
    print(A.numer)  # A
    deque 是为了高效实现插入和删除操作的双向列表,适合用于队列和栈
    队列:先进先出(FIFO)
    import queue q = queue.Queue() # 生成队列对象 q.put('first') q.put('second') print(q.get()) # first print(q.get()) # second 如果队列中的值取完了,程序会在原地等待,直到从队列中取到值 deque 双端队列 from collections import deque q = deque(['a','b','c']) q.append(0) q.appendleft(1) print(q) q.insert(1,'哈哈') print(q.popleft()) #1 print(q.popleft()) # 哈哈 print(q.pop()) # 0
    OrderedDict  使用dict时,Key无序,对dict做迭代时,无法确认Key的顺序,想保持Key的顺序,用OrderedDict: 
    normal_d = dict([('a',1),('b',2),('c',3)]) print(normal_d) # {'a': 1, 'b': 2, 'c': 3} from collections import OrderedDict order_d = OrderedDict([('a',1),('b',2),('c',3)]) print(order_d) # OrderedDict([('a', 1), ('b', 2), ('c', 3)]) order_d1 = OrderedDict() order_d1['x'] = 1 order_d1['y'] = 2 print(order_d1) #OrderedDict([('x', 1), ('y', 2)]) for i in order_d1: print(i) # x y
    defaultdict  在使用dict时,如果引用的key不存在,就会报错,如果希望key不存在,返回一个默认值,就用defaultdict:
    from
    collections import defaultdict values = [11, 22, 33,44,55,66,77,88,99,90] my_dict = defaultdict(list) print(my_dict['aaa']) # [] for value in values: if value > 66: my_dict['k1'].append(value) else: my_dict['k2'].append(value) print(my_dict) # defaultdict(<class 'list'>, {'aaa': [], 'k2': [11, 22, 33, 44, 55, 66], 'k1': [77, 88, 99, 90]}) my_dict1 = defaultdict(bool) print(my_dict1['xxx']) #False my_dict1 = defaultdict(int) print(my_dict1['yyy']) #0 my_dict1 = defaultdict(tuple) print(my_dict1['kkk']) # ()
    Counter 计数器,主要用来计数
    from collections import Counter s = 'dsfjdjf' res = Counter(s) print(res) #Counter({'d': 2, 'f': 2, 'j': 2, 's': 1}) for i in res: print(i) # d s f g d = {} for i in s: d[i] = 0 print(d) # {'d': 0, 's': 0, 'f': 0, 'j': 0}

    time

    三种表现形式

    1.时间戳

    2.格式化时间

    3.结构化时间

    import time
    print(time.time())  # 1563447208.9203036   时间戳
    
    print(time.strftime('%Y-%m-%d'))  # 2019-07-18    格式化时间
    print(time.strftime('%Y-%m-%d %H:%M:%S'))  # 2019-07-18 18:53:28
    print(time.strftime('%Y-%m-%d %X'))  # 2019-07-18 18:53:28
    
    print(time.localtime())  # time.struct_time(tm_year=2019, tm_mon=7, tm_mday=18, tm_hour=18, tm_min=53, tm_sec=28, tm_wday=3, tm_yday=199, tm_isdst=0)   结构化时间
    print(time.localtime(time.time()))  # time.struct_time(tm_year=2019, tm_mon=7, tm_mday=18, tm_hour=18, tm_min=53, tm_sec=28, tm_wday=3, tm_yday=199, tm_isdst=0)
    
    print(time.strftime('%Y-%m',time.localtime()))  # 2019-07
    print(time.strptime(time.strftime('%Y-%m',time.localtime()),'%Y-%m'))  # time.struct_time(tm_year=2019, tm_mon=7, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=182, tm_isdst=-1

    时间戳<->结构化时间<->格式化时间

    date:年月日  datetime:年月日 时分秒

    import datetime
    res = datetime.date.today()
    print(res.year)  # 2019
    print(res.weekday())  # 3  0-6表示星期,   0表示是的星期一
    print(res.isoweekday())  # 4    1-7表示星期  7表示周日
    
    current_time = datetime.date.today()  # 日期对象
    timetel_t = datetime.timedelta(days = 7)  #timetel_t对象
    res1 = current_time + timetel_t  # 日期对象
    print(current_time - timetel_t)  #2019-07-11
    print(res1 - current_time)  # 7 days, 0:00:00
    # 日期对象 = 日期对象 +- timetel_t对象
    timetel_t对象 = 日期对象 +- 日期对象
    dt_today = datetime.datetime.today()
    dt_now = datetime.datetime.now()
    dt_utcnow = datetime.datetime.utcnow()
    print(dt_utcnow,dt_now,dt_today) # 2019-07-18 11:33:40.377819 2019-07-18 19:33:40.377819 2019-07-18 19:33:40.377820
    import random
    print(random.randint(1,6))  # 1  随机在1-6中选取一个整数,包含首尾
    
    print(random.random())  # 0.8314242946112116  随机在0-1之间生成一个小数
    
    print(random.choice([1,2,3,4,5,6]))  # 4  摇号 随机在列表中取一个元素
    
    res = [1,2,3,4,5,6]  #洗牌
    random.shuffle(res)
    print(res)   #[1, 3, 5, 6, 4, 2]
    大写字母 小写字母 数字
    4位数的随机验证码
    封装成一个函数,用户想生成几位就生成几位
    import random
    def get_code(n):
        code = ''
        for i in range(n):
            upper_str = chr(random.randint(65,90))  # 随机生成大写字母
            lower_str = chr(random.randint(97,122))  #随机生成小写字母
            random_int = str(random.randint(0,9))  #随机生成数字
            code += random.choice([upper_str,lower_str,random_int])#从三个当中随机选择一个作为验证码的某一位
        return code
    res = get_code(4)
    print(res)  #J23T

    os 模块:跟操作系统打交道的模块

    sys模块:和python解释器打交道的模块

    os.path.join(path1, [path2])   # 将多个路径组合后返回,

    BASE_DIR = os.path.dirname(__file__) #返回path的目录,
    os.listdir('D:python_workspaceday16') # 返回的是一个列表,列表中的元素是path路径下的所有文件

    os.mkdir('dirname')  #自动创建目录

    os.path.exists(path)  #如果path存在,返回True;如果path不存在,返回False

    os.path.isfile(path)  #判断文件是否存在,如果存在True,不存在False

    os.rmdir('dirname')   #只能删除空文件夹

    os.getcwd()    # 获取当前工作目录,

    os.chdir('dirname')  # 切换当前所在的目录

    os.path.getsize(path)  # 返回path的大小

    os.remove()

    os.rename()  文件修改

    import sys
    sys.path.append()  # 将某个路径添加到系统的环境变量中
    print(sys.platform)  # win32
    print(sys.version)  # python解释器的版本    3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)]

    sys.argv() 是一个列表,列表中的每一个元素,就是位于python命令之后一个个值

    序列化:   序列的对象为字符串

     dumps  序列化:其他数据类型转化为字符串类型的过程

     loads   反序列化:字符串转化为其他数据类型

      json的dumps功能: 其他数据类型转化为字符串类型的过程      res = json.dumps(d)

      json的dump功能:  将其他数据类型直接转换成json字符串写入文件    json.dump(d,f)

      json的loads功能:  处理字符串类型的字典,  字典中的字符串必须由""表示   res = json.dumps(d)         res1 = json.loads(res)

      json的load功能:  接收一个文件句柄,直接将文件中的json字符串转换成数据结构返回    res = json.load(f)

    json模块

      所有的语言都支持json格式,   支持的数据类型少  字符串  列表  字典  整形  元组(转成列表) 布尔值

    pickle模块

      只支持python,但支持python的所有数据类型

    import json
    d = {'name':'jason'}
    print(d,type(d))  #{'name': 'jason'} <class 'dict'>  json格式的字符串 必须是双引号 >>>: '{"name": "jason"}'
    res = json.dumps(d)
    print(res,type(res))  # {"name": "jason"} <class 'str'>
    with open('userinfo','w',encoding='utf-8') as f:
        json.dump(d,f)  # 将字符串自动写入文件     dump方法接收一个文件句柄,直接将字典转换成json字符串写入文件
    with open('userinfo','r',encoding='utf-8') as f:
        res = json.load(f)    #load方法接收一个文件句柄,直接将文件中的json字符串转换成数据结构返回
        print(res,type(res))  # {'name': 'jason'} <class 'dict'>
    import pickle
    d = {'name':'jason'}
    res = pickle.dumps(d)
    res1 = pickle.loads(res)
    print(res1,type(res1))  # {'name': 'jason'} <class 'dict'>
    
    with open('userinfo_1','wb') as f:
        pickle.dump(d,f)
    with open('userinfo_1','rb') as f:
        res = pickle.load(f)
        print(res,type(res))  # {'name': 'jason'} <class 'dict'>
    import json
    from datetime import datetime,date
    print(datetime.today())   # 2019-08-06 18:48:19.437915
    print(date.today())    # 2019-08-06
    class Myjson(json.JSONEncoder):
        def default(self,o):
            if isinstance(o,datetime):
                return o.strftime('%Y-%m-%d %X')
            elif isinstance(o,date):
                return o.strftime('%Y-%m-%d')
            else:
                return super().default(self,o)
    res = {'c1':datetime.today(),'c2':date.today()}
    print(json.dumps(res,cls = Myjson))   # {"c1": "2019-08-06 18:48:19", "c2": "2019-08-06"}

    subprocess 子进程

    """
    1.用户通过网络连接上了你的这台电脑
    2.用户输入相应的命令 基于网络发送给了你这台电脑上某个程序
    3.获取用户命令 里面subprocess执行该用户命令
    4.将执行结果再基于网络发送给用户
    这样就实现  用户远程操作你这台电脑的操作
    """

    dayehui
  • 相关阅读:
    JSON格式化
    mysql字符串操作
    MySLQ排序后标记排行
    RestTemplate调用POST接口
    FULLTEXT INDEX全文索引
    Convert AS400 Spool to PFD Tools – PDFing
    openssl制作双向认证经过验证可行
    https web service in Tibco & PC
    Python获取百度浏览记录
    Python2.7学习
  • 原文地址:https://www.cnblogs.com/zrh-960906/p/11210558.html
Copyright © 2011-2022 走看看