python学习之路---day21--模块和栈

                                        模块和栈

一:计数模块collections
基础版本:
s="qwewsfdfjiehrfqweqweqwqewq"
        dic={}
        for el in s:
            dic[el]=dic.setdefault(el,0)+1
        print(dic)
    升级版本:
import collections
        from collections import Counter
        s="qwewsfdfjiehrfqweqweqwqewq"
        qq=Counter(s)
        print("__iter__" in dir(qq))
        for item in qq:
            print(item,qq[item])

 # 同时列表也可以用counter
    # # 列表也可以用Counter
        import collections
        lst=["1","2","1","1","4","1"]
        q=collections.Counter(lst)
        print(q)  #打印: Counter({'1': 4, '2': 1, '4': 1})
二:栈和队列
001:栈
栈的进出原则:先进后出
栈的基本知识点总结:
 栈是一种先进后出的序列表,先放进去的元素,只能通过栈指针去取出来,每当放入一个元素的时候当往栈里面添加一个元素时,
    栈指针会往上移动一个(index会变成 index+1--〉放元素时),取元素的时候,也是通过栈指针,取指针的下一个元素,此时栈
    顶指针是:  index=index-1(取元素时),,,空栈的时候添加元素只能用插入--〉insert()
    自定义栈满了之后的异常
class StackFullError(Exception):
        pass

    class StackEmptyError(Exception):
        pass

    class Stack:  #定义一个栈类
        def __init__(self,size):
            self.index=0  #栈顶指针
            self.lst=[]
            self.size=size

        def push(self,item):  #往栈里面添加元素
            if self.index==self.size:
                #栈已经满了   需要报错
                raise StackFullError("the Stack is full")

            self.lst.insert(self.index,item)  #空列表需要用insert
            self.index+=1
  #从栈中获取数据
  
def pop(self):
            if self.index==0:
                raise StackEmptyError("the stack is empty")  #这里也需要自定义一个异常(栈空了需要报异常)
            self.index-=1  #指针向下移动
            item=self.lst.pop(self.index)  #获取元素删除
            return item

    s=Stack(5)  #给栈一个大小
    s.push("q")
    s.push("w")
    s.push("e")
    s.push("r")
    s.push("t")  #往栈里面添加元素

    print(s.pop())   #从栈里面拿数据元素
    print(s.pop())
    print(s.pop())
    print(s.pop())
    print(s.pop())
    print(s.pop())

    print(s.pop())  #超出栈大小,抛出异常
View Code
  02):队列
队列数据进出原则:先进先出
  例子01:
  
import queue   #引入队列模块
    q=queue.Queue()  #创建一个队列,固定模板(在queue模块中有一个)
    q.put("张三")
    q.put("李四")
    q.put("王五")
    q.put("旺财")
    q.put("小白")

    print(q.get())
    print(q.get())
    print(q.get())
    print(q.get())
    print(q.get())
    #打印:张三  李四   王五  旺财  小白
    #
    print(q.get())  #造成阻塞
    print("没有了")
    #在队列里面已经没有元素了,还继续拿元素的时候,队列会一直处于执行状态,等待着元素的进入,这个时候就是阻塞了
View Code
  03):双向队列
  
from collections import deque  #从系统中自带的collections 模块 引入 deque
    q=deque() #创建一个双向队列

    q.append("张三")  #从右边末尾开始加元素
    q.append("李斯特") #加在最右边,提取数据时候,总是从最右边开始获取

    q.appendleft("王五")  #加在最左边,提取的时候总是从最左边开始获取数据
    q.appendleft("旺财")

    print(q.pop())  #从最右边开始获取
    print(q.popleft()) #从最左边开始获取
View Code
  04):namedtuple  #命名元组
  
from collections import namedtuple
    Point=namedtuple("",["x","y","z"])
    p=Point("zhangshan","lisu","王五")
    print(p)
    print(p.x)
    print(p.y)
    print(p.z)

    类似于:
    class Point:
        def __init__(self,x,y):
            self.x=x
            self.y=y
    p=Point(2,3)
    p.z=12
    print(p.z)
View Code
  05):默认字典 defaultdict
  
例子01:
    from collections import defaultdict
    lst=[11,22,33,44,55,66,77,88,99]
    d=defaultdict(list)   #d是一个空列表
    for el in lst:
        if el<66:
            d["key1"].append(el)   #d["key1"]  是一个字典的键,将el 添加到其所对应的键值的列表中
        else:
            d["key2"].append(el)  #key1 key2 是不存在的,但是可以拿到key1 key2
    print(d)

  例子2:
    from collections import defaultdict
    d=defaultdict(list)
    #d=defaultdict(abc)    abc 可以是list、set、str等等,作用是当key不存在时,
    # 返回的是abc的默认值,比如list对应[ ],str对应的是空字符串,
    d["wangwu"]="王五"
    print(d["zhangsan"])  #打印:[]
    print(d["wangwu"])  #打印:王五
View Code
  06):orderdict和defaultdict
  orderdict 顾名思义. 字典的key默认是⽆序的. ⽽OrderedDict是有序的
    dic = {'a':'娃哈哈', 'b':'薯条', 'c':'胡辣汤'}
    print(dic)
    from collections import OrderedDict
    od = OrderedDict({'a':'娃哈哈', 'b':'薯条', 'c':'胡辣汤'})  #从这个3.6版本是看不出来的,但是内部是无序的
    print(od)
三:时间模块
获取当前时间 (时间戳)
001:打印本地时间(时间有localtime 和 gmtime )
  import time
    print(time.time()) #d打印的时当前时间:1542167144.751588
  002格式化时间:
  s=time.strftime("%Y/%m/%d %H:%M:%S")  #string format time
    print(s)  #打印:2018/11/14 11:48:02
    相似类等待时间 :wait()  #傻等,必须要是 notify()
    例子:
    while 1:   #这是一个计时器
        s=time.strftime("%Y-%m-%d %H:%M:%S")
        print(s)
        time.sleep(2)  #每隔(睡眠) 2秒 然后再执行打印
  003:结构化时间:
  import time
    t=time.localtime()
    print(t)
    #打印:time.struct_time(tm_year=2018, tm_mon=11, tm_mday=14, tm_hour=11, tm_min=55, tm_sec=22, tm_wday=2, tm_yday=318, tm_isdst=0)
    print(t.tm_year)  #只获取年份,其他的分 秒类似写法
  004:将时间戳转换成格式化时间
  
时间戳--〉格式化时间:
    import time
    a=19888899
    t=time.localtime(a)
    #t=time.gmtime(0)   #时区   gmtime() 格林尼治时间
    print(t)  #打印:time.struct_time(tm_year=1970, tm_mon=8, tm_mday=19, tm_hour=12, tm_min=41, tm_sec=39, tm_wday=2, tm_yday=231, tm_isdst=0)
    str_time=time.strftime("%Y/%m/%d %H:%M/%S:%A/%Z",t)
    print(str_time)  #打印:1970/08/19 12:41/39:Wednesday

    格式化时间--〉时间戳(思路:格式化时间--〉结构化时间--〉时间戳)

    import time
    # 格式化时间--〉结构化时间
    s="2017-2-23 13:45:34"
    t=time.strptime(s,"%Y-%m-%d %H:%M:%S")
    print(t)  #打印:time.struct_time(tm_year=2017, tm_mon=2, tm_mday=23, tm_hour=13, tm_min=45, tm_sec=34, tm_wday=3, tm_yday=54, tm_isdst=-1)
    # 结构化时间--〉时间戳
    tt=time.mktime(t)
    print(tt) #打印:1487828734.0
View Code
  案例:
时间戳和格式化 结构化时间的相互转换(用两种方法写)
例子:
计算时间差(用户输入起始时间和结束时间. 计算时间差(小时),
例如, 用户输入 2018-10-08 12:00:00 2018-10-08 14:30:00 输出 2 小时30分
方法一:
  
思路:格式化时间--〉结构化时间-->时间戳  然后时间戳相减,得到差值,将差值进行转为结构化时间输出
    import time
    a1="2018-10-08 12:00:00"
    a2="2018-10-08 14:30:00"
    t1=time.strptime(a1,"%Y-%m-%d %H:%M:%S")  #格式化时间转换为结构化时间  time.strptime(string,format)
    #print(t1) #time.struct_time(tm_year=2018, tm_mon=10, tm_mday=8, tm_hour=12, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=281, tm_isdst=-1)
    t2=time.strptime(a2,"%Y-%m-%d %H:%M:%S")  #格式化时间转换为结构化时间  time.strptime(string,format)
    #print(t2) #time.struct_time(tm_year=2018, tm_mon=10, tm_mday=8, tm_hour=14, tm_min=30, tm_sec=0, tm_wday=0, tm_yday=281, tm_isdst=-1)

    tt1=time.mktime(t1)  #将结构化时间通过time.mktime() 转换为时间戳
    # print(tt1)  #1538971200.0
    tt2=time.mktime(t2) #将结构化时间通过time.mktime() 转换为时间戳
    # print(tt2)   #1538980200.0
    tt_new=int(abs(tt1-tt2))   #不知道=谁减去谁,直接一个abs()绝对值就可以了
    # print(tt_new)  #9000
    tt_last=time.gmtime(tt_new) #在将时间戳转换为结构化时间(不要用time.localtime()  不然会有8小时的时区差)
    print(tt_last)  #  time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=2, tm_min=30, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)
    print("时间差了%d年%d月%d天%d小时%d分钟%d秒" % (tt_last.tm_year-1970,tt_last.tm_mon-1, tt_last.tm_mday-1,tt_last.tm_hour, tt_last.tm_min, tt_last.tm_sec))
View Code
  方法二:
  
思路:也是分别将给定的格式化时间转换为时间戳,然后将时间戳转换为结构化时间
    import time
    a1="2018-10-08 12:00:00"
    a2="2018-10-08 14:30:00"
    t1=time.strptime(a1,"%Y-%m-%d %H:%M:%S")  #格式化时间转换为结构化时间  time.strptime(string,format)
    t2=time.strptime(a2,"%Y-%m-%d %H:%M:%S")  #格式化时间转换为结构化时间  time.strptime(string,format)
    tt1=time.mktime(t1)  #将结构化时间通过time.mktime() 转换为时间戳
    tt2=time.mktime(t2) #将结构化时间通过time.mktime() 转换为时间戳
    tt_new=int(abs(tt1-tt2))   #不知道谁减去谁,直接一个abs()绝对值就可以了
    print(tt_new)  #9000  这个是秒
    tt_Hour=tt_new//3600
    print(tt_Hour)  #显示出:小时  2
    tt_Min=int((tt_new-tt_Hour*3600)/60) #显示出来还剩下多少分钟
    print(tt_Min)  #显示出来分钟  30
    print("时间差是%s小时%s分钟" % (tt_Hour,tt_Min))
View Code

  ⽇期格式化的标准:
  
%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 当前时区的名称
    %% %号本身
View Code
四:random 模块
import random  #引入随机数模块
    print(random.randint(1,9))  #1到9 随机产生 一个整数  (前闭后闭  可以取到9)
    print(random.random())  #随机产生一个(0,1)之间的小树
    print(random.choice([1,"张三",["李四","王五","赵四"]]))  # 从这些元素中随机产生一个
    print(random.sample([["1","2","3"],"旺财","小白",123],2))   #2 代表从这些数据中随机产生2个出来组成,可也可以改成其他3等等

    lst=[14,6,8,2,32,1,90,7]
    random.shuffle(lst)
    print(lst)  #每次返回的数据都不一样。random对其顺序打乱了
    lst的返回值为None
五:os模块(所有的和操作系统相关的内容都在os模块)
  
import os
    os.makedirs("123/345")  #可⽣成多层递归⽬录
    os.removedirs("123")   #FileExistsError: [WinError 183] 当文件已存在时,无法创建该文件。: '123/345'
    os.removedirs("123/345")  #删除123文件夹下的345文件夹或则文件,如果文件夹下有其他文件,则无法进行删除操作
    os.mkdir('123') #生成单级目录;相当于shell中mkdir dirname
    os.rmdir('123') #删除单级空⽬录,若⽬录不为空则⽆法删除,报错;相当于shell中
    print(os.listdir("../整理--day019 约束和异常处理/"))  #返回指定的文件夹包含的文件或文件夹的名字的列表。这个列表以字母顺序
    os.remove("123/234")  #删除123文件夹下的234文件(或则文件夹) ,当234文件夹内有内容时,无法删除
    os.rename("oldname","newname") 重命名⽂件/⽬录
    os.stat('path/filename')   获取⽂件/⽬录信息
    os.system("bash command")  #运⾏shell命令,直接显示
    os.popen("bash command").read()  #运⾏shell命令,获取执⾏结果
    os.getcwd() 获取当前⼯作⽬录,即当前python脚本⼯作的⽬录路径
    os.chdir("dirname") 改变当前脚本⼯作⽬录;相当于shell下cd

    os.path
    os.path.abspath(path) 返回path规范化的绝对路径
    os.path.split(path) 将path分割成⽬录和⽂件名⼆元组返回
    os.path.dirname(path) 返回path的⽬录。其实就是os.path.split(path)的第⼀个元素
    os.path.basename(path) 返回path最后的⽂件名。如何path以/或结尾,那么就会返回空值。
    即os.path.split(path)的第⼆个元素
    os.path.exists(path) 如果path存在,返回True;如果path不存在,返回False
    os.path.isabs(path) 如果path是绝对路径,返回True
    os.path.isfile(path) 如果path是⼀个存在的⽂件,返回True。否则返回False
    os.path.isdir(path) 如果path是⼀个存在的⽬录,则返回True。否则返回False
    os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第⼀个绝对路径之前的参数
    将被忽略
    os.path.getatime(path) 返回path所指向的⽂件或者⽬录的最后访问时间
    os.path.getmtime(path) 返回path所指向的⽂件或者⽬录的最后修改时间
    os.path.getsize(path) 返回path的⼤⼩
    # 特殊属性:
    os.sep 输出操作系统特定的路径分隔符,win下为"\",Linux下为"/"
    os.linesep 输出当前平台使⽤的⾏终⽌符,win下为"
",Linux下为"
"
    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)是创建时间(详细信息参⻅平台的⽂档)。
View Code
六. sys模块
所有和python解释器相关的都在sys模块.
sys.argv 命令⾏参数List,第⼀个元素是程序本身路径
    sys.exit(n) 退出程序,正常退出时exit(0),错误退出sys.exit(1)
    sys.version 获取Python解释程序的版本信息
    sys.path 返回模块的搜索路径,初始化时使⽤PYTHONPATH环境变量的值
    sys.platform 返回操作系统平台名称



原文地址:https://www.cnblogs.com/one-tom/p/9960253.html