• Python中5大模块的使用教程(collections模块、time时间模块、random模块、os模块、sys模块)


    1. 模块的简单认识

    定义:

    模块就是我们把装有特定功能的代码进行归类的结果.

    从代码编写的单位来看我们的程序,从小到大的顺序: 一条代码 < 语句块 < 代码块(函数,类) < 模块.
    我们⽬目前写的所有的py文件都是模块.
    引入模块的方式:

    • import 模块
    • from xxx import 模块

    2. collections模块

    collections模块主要封装了一些关于集合类的相关操作. 比如, 我们学过的Iterable,Iterator等.
    另外,collections还提供了一些除了基本据类型以外的数据集合类型.Counter,deque,OrderDict,defaultdict以及namedtuple

    2.1 counter(counter主要用于计数)

    实例1:

    from collections import Counter
    s = "i have a dream,do you konw ?"
    dic = {}
    for el in s:
        dic[el] = dic.setdefault(el,0) + 1
    print(dic)
    
    sum = Counter(s)
    print(sum)
    for el in sum:
        print(el,sum[el])
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    2.22. deque 双向队列.

    (重点)说双向队列之前我们需要了解两种数据结构. 1.栈, 2.队列

    • 栈: FILO. 先进后出 -> 砌墙的砖头, 老师傅做馒头
    • 队列: FIFO. 先进先出 -> 买火车票排队, 所有排队的场景

    栈: python没有给出Stack模块.所以我写了一个粗略版本(注意,此版本有严重的并发问题)

    实例:

    class StackFullError(Exception):
        pass
    class StackEmptyError(Exception):
        pass
    
    class Stack():
        def __init__(self,size):
            self.size = size
            self.lis = []
            self.index = 0
        def push(self,item):
            if self.index >= self.size:
                raise StackFullError("The Stack is full")
            self.lis.insert(self.index,item)
            self.index += 1
        def pop(self):
            if self.index == 0:
                raise StackEmptyError("The Stack is empty")
            self.index -= 1
            s = self.lis.pop()
            return s
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    队列: python提供了queue模块. 使用起来非常方便
    实例:

    import queue
    q = queue.Queue()
    q._put("王大锤")
    q.put("王尼玛")
    print(q.get())
    print(q.get())
    print(q.get())   #若队列里面的元素取完了,会阻塞在这里.直到有元素进来才会往前走"
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    deque:双向队列,属于collections
    实例:

    from collections import deque
    q = deque()
    q.append("仙都酱板鸭")
    q.append("久久丫")
    q.appendleft("周黑鸭")
    q.appendleft("绝味鸭脖")
    print(q)
    print(q.pop())
    print(q.popleft())
    print(q.popleft())
    print(q.popleft())
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    2.3. namedtuple 命名元组

    命名元组, 顾名思义. 给元组内的元素进行命名. 比如. 我们说(x, y) 这是一个元组.
    同时. 我们还可以认为这是一个点坐标. 这时, 我们就可以使⽤namedtuple对元素进行命名.
    实例

    from collections import namedtuple
    point = namedtuple("point1",["x","y"])
    p = point(2,4)
    print(p)
    
    • 1
    • 2
    • 3
    • 4
    2.4. orderdict和defaultdict

    orderdict:有序字典 在Python中基本不用了,因为其顺序3.6以后的字典一样的
    defaultdict:默认值字典

    from collections import defaultdict
    lst= [11,22,33,44,55,66,77,88,99]
    d = defaultdict(list)      #defaultdict(可被调用的对象)   括号内必须为可被调用的对象
    for el in lst:
        if el < 66:
            d["key1"].append(el) # key1默认是不存在的. 但是可以拿key1. 一个空列表.
        else:
            d["key2"].append(el)
    print(d)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    tip:如何让默认返回值是字符串?? 用函数!!!

    from collections import defaultdict
    def func():
        return "周黑鸭"
    d = defaultdict(func)
    print(d["哈哈"])
    print(d)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    3. time时间模块

    时间模块是我们要熟记的.到后面写程序的时候经常能用到.比如,如何计算时间差.如何按照客户的要求展示时间

    在python中时间分成三种表现形式:

    • 时间戳(timestamp). 时间戳使用的是从1970年01月01日 00点00分00秒到现在一共经过了多少秒…使用float来表示
    • 格式化时间(strftime). 这个时间可以根据我们的需要对时进行任意的格式化.
    • 结构化时间(struct_time).这个时间主要可以把时间进行分类划分.
    • 比如.1970年01⽉01⽇ 00点00分00秒 这个时间可以被细分为年, 月, 日…一大堆东⻄西.

    获取时间戳

    import time
    print(time.time())  # 1538927647.483177 系统时间 不能展示给客户
    
    • 1
    • 2

    格式化时间

    import time
    s = time.strftime("%Y-%m-%d %H:%M:%S")  # 必须记住
    print(s)
    
    • 1
    • 2
    • 3

    日期格式化的标准:

    %y 两位数的年份表示(00-99%Y 四位数的年份表示(000-9999%m 月份(01-12%d 月内中的⼀一天(0-31%H 24小时制小时数(0-23%I 12小时制小时数(01-12%M 分钟数(00=59%S 秒(00-59%a 本地简化星期名称
    %A 本地完整星期名称
    %b 本地简化的月份名称
    %B 本地完整的月份名称
    %c 本地相应的日期表示和时间表示
    %j 年内的一天(001-366%p 本地A.M.或P.M.的等价符
    %U 一年年中的星期数(00-53)星期天为星期的开始
    %w 星期(0-6),星期天为星期的开始
    %W 一年中的星期数(00-53)星期一为星期的开始
    %x 本地相应的日期表示
    %X 本地相应的时间表示
    %Z 当前时区的名称
    %% %号本身
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    结构化时间:

    print(time.localtime())
    
    • 1

    结果:

    import time
    time.struct_time(tm_year=2017, tm_mon=05, tm_mday=8, tm_hour=10, tm_min=24,
    tm_sec=42, tm_wday=0, tm_yday=126, tm_isdst=0)
    
    • 1
    • 2
    • 3

    时间戳和格式化时间之间如何转换??

    从时间戳 -> 格式化时间

    import time
    t = time.localtime(1542513992) # 时区   gmtime() 格林尼治时间. 根据不同时区时间local或qm
    print(t)
    str_time = time.strftime("%Y-%m-%d %H:%M:%S", t)   #时间戳转为格式化时间
    print(str_time)
    
    • 1
    • 2
    • 3
    • 4
    • 5

    用户输入一个时间. 变成时间戳

    • 格式化时间 -> 时间戳
    • 格式化时间->结构化时间
    import time
    2018-11-18 12:06:32
    s = "2018-11-18 12:06:32"
    t = time.strptime(s, "%Y-%m-%d %H:%M:%S") # 结构化时间 string parse time
    print(t)
    # 结构化时间 -> 时间戳
    ss = time.mktime(t)
    print(ss)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    那有如何计算时间差呢?

    begin = "2018-11-14 16:30:00"
    end = "2018-11-14 18:00:00"   # 时间差  1小时30分
    # 格式化时间->结构化时间
    begin_struct_time = time.strptime(begin, "%Y-%m-%d %H:%M:%S")
    end_stract_time = time.strptime(end, "%Y-%m-%d %H:%M:%S")
    #结构化时间->时间戳
    begin_second = time.mktime(begin_struct_time)
    end_second = time.mktime(end_stract_time)
    
    # 秒级的时间差   180000
    #用时间戳计算出时间差(秒)
    diff_time_sec = abs(begin_second - end_second)
    
    # 转换成分钟
    diff_min = int(diff_time_sec//60)
    print(diff_min)
    
    diff_hour = diff_min//60  # 1
    diff_min_1 = diff_min % 60 # 30
    # 变成想要的时间格式
    print("时间差是 %s小时%s分钟" % (diff_hour, diff_min_1))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    tips:格式化时间和时间戳之间的转化和时间差的计算很重要,一定要会写!!!

    4. random模块

    所有关于随机相关的内容都在random模块中.

    import random
    print(random.random())        #随机生成小数
    print(random.randint(1,4))         #随机生成范围内的整数
    print(random.uniform(1,10))           #随机生成范围内的小数
    print(random.randrange(1,10,2))    #随机生成范围内的根据步长取值的整数
    print(random.choice([1, 10, 2,"嘿嘿"]))  # 随机取[]内的值
    print(random.sample([1, 10, 2,"嘿嘿"],3))  #随机抽取列表内元素进行随机组合,组合个数根据后面填的值决定
    lst = [1, 2, 3, 4, 5, 6, 7, 8]
    random.shuffle(lst)                      # 随机打乱顺序
    print(lst)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    5. os模块

    os:

    os.makedirs('dirname1/dirname5') # 创建文件夹目录结构
    os.removedirs('dirname1/dirname5')  # 删除文件夹, 如果文件夹内没有东西。 就可以删除。 否则报错
    
    os.mkdir('dirname/哈哈')  # mkdir如果父级目录不存在。 报错
    os.rmdir('dirname') # 删除文件夹
    
    print(os.listdir('../')) # 获取到文件夹内的所有内容. 递归
    
    print(os.stat('dirname')) # linux
    
    os.system("dir") # 直接执行命令行程序
    s = os.popen("dir").read()
    print(s)
    # python学习交流群:711312441
    print(os.getcwd() ) # 当前程序所在的文件夹
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    os.path:

    print(os.path.abspath("../day020 继承") ) # 获取绝对路径
    print(os.path.split("D:\python_workspace\day020 继承")) # 拆分路径 ('D:\\python_workspace', 'day020 继承')
    print(os.path.dirname("D:\python_workspace\day020 继承")) # D:\python_workspace
    print(os.path.basename("D:\python_workspace\day020 继承")) # day020 继承
    
    print(os.path.exists("dirname")) # 判断文件是否存在
    print(os.path.isabs("D:\python_workspace\day020 继承")) # 是否是绝对路径
    print(os.path.isfile("01 今日主要内容")) # 是否是文件
    print(os.path.isdir("dirname")) # 是否是文件夹
    print(os.path.getsize("01 今日主要内容") ) # 文件大小
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    特殊属性:

    os.sep 输出操作系统特定的路路径分隔符,win下为"\\",Linux下为"/"
              print("c:"+os.sep+"胡辣汤") # \\/  文件路径的分隔符
    os.linesep 输出当前平台使⽤用的行终止符,win下为"\r\n",Linux下为"\n"
    os.pathsep 输出⽤于分割⽂文件路径的字符串串 win下为;   Linux下为 :
    os.name 输出字符串串指示当前使⽤用平台。win->'nt'; Linux->'posix'
    
    os.stat() 属性解读:
    # stat 结构:
    st_mode: inode 保护模式
    st_ino: inode 节点号。
    st_dev: inode 驻留的设备。
    st_nlink: inode 的链接数。
    st_uid: 所有者的⽤用户ID。
    st_gid: 所有者的组ID。
    st_size: 普通⽂文件以字节为单位的大小;包含等待某些特殊文件的数据。
    st_atime: 上次访问的时间。
    st_mtime: 最后⼀次修改的时间。
    st_ctime: 由操作系统报告的"ctime"。在某些系统上(如Unix)是最新的元数据更更改的时间,
               在其它系统上(如Windows)是创建时间(详细信息参见平台的⽂文档)。
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    6. sys模块

    所有和python解释器相关的都在sys模块.

    • sys.argv 命令行参数List,第一个元素是程序本身路径
    • sys.exit(n) 退出程序,正常退出时exit(0),错误退出sys.exit(1)
    • sys.version 获取Python解释程序的版本信息
    • sys.path 返回模块的搜索路径,初始化时使⽤PYTHONPATH环境变量的值
    • sys.platform 返回操作系统平台名称

    tips:os 和 sys中比较重要的两个模块用法

    • os.sep 文件路径分隔符
    • sys.path python查找模块的路径
  • 相关阅读:
    [UE]常见C++类继承关系
    REDIS09_HyperLogLog的概述、基本命令、UV、PV、DAU、MAU、首页UV如何进行统计处理
    基于ssm技术的校自助阅览室的设计与实现毕业设计源码242326
    Spring Cloud项目(四)——使用Ribbon作为负载均衡
    2022 年 前40道 ReactJS 面试问题和答案
    mongoose 查询返回的数据无法更改问题
    虚机的部分磁盘空间被谁吃了?
    如何优雅的实现 iframe 多层级嵌套通讯
    攻防世界maze做法(迷宫题)
    基于JavaGUI的图书管理系统
  • 原文地址:https://blog.csdn.net/qdPython/article/details/128116474