day21 常用模块01

一. 模块

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

 引入模块的方式: 1. import 模块  2. from xxx import 模块

二. collections  集合类的操作, 除了基础数据类型以外的数据集合类型

  1. Counter 计数器

s = "I am sylar, I have a dream, freedom...."
dic = {}
for el in s:
    dic[el] = dic.setdefault(el, 0) + 1  # get 也可以
print(dic)

from collections import Counter

print(Counter(s))  # 结果是字典类型的

 

  2. deque 双向队列

   (重要的数据结构)  1. 栈: FILO 先进后出 -> 砌墙的砖头,  2. 队列: FIFO 先进先出 -> 所有排队的场景

  注意: python本身没有提供栈, 但是list本身就是一个栈

# python 写一个栈程序
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.append(self.index, item)  # 根据栈顶指针的位置, 插入对应元素
        self.index += 1  # 栈顶指针向下移动
        
    # 从栈中获取(删除)数据
    def pop(self):
        if self.index is 0:  #  判断栈顶指针是否再最上面
            raise StackEmptyError('the stack is empty')
        self.index -= 1  # z指针向下移动
        item = self.lst.pop(self.index)  # 获取元素删除
        return item  # 返回删除的元素, 即可以提取栈内元素
        
s = Stack(5)
s.push("馒头1号")
s.push("馒头2号")
s.push("馒头3号")
s.push("馒头4号")
s.push("馒头5号")

print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())

 

# 队列
import queue
#
q = queue.Queue() # 创建队列
q.put("李嘉诚")
q.put("陈冠希")
q.put("周润发")
q.put("吴彦祖")

print(q.get())
print(q.get())
print(q.get())
print(q.get())
# print(q.get()) # 队列中如果没有元素了. 继续获取的话. 会阻塞
print("拿完了")
from collections import deque

q = deque() # 创建一个双向队列
q.append("高圆圆")
q.append("江疏影")
q.appendleft("赵又廷")
q.appendleft("刘大哥")
#  刘大哥 赵又廷 高圆圆 江疏影
print(q.pop()) # 从右边获取数据
print(q.pop())
print(q.popleft()) # 从左边获取数据
print(q.popleft())
print(q.pop())  # IndexError: pop from an empty deque

# 注意双向队列的左右方向

  3. nametuple 命名元组

  顾名思义, 给元组内的元素进行命名

from collections import namedtuple

point = namedtuple("Point", ["x", "y", 'z']) # 这个就相当于写了一个类
# class point:
#     def __init__(self, x, y):
#         self.x = x
#         self.y = y

p = point(5, 18, 88)
print(p.x)
print(p.y)
# p.x = 19 # AttributeError: can't set attribute  终归是元组不能修改
print(p)

  4. orderdict 和 defaultdict

    orderdict 顾名思义, 字典的key是无序的(字典的底层是hash), 而OrderedDict是有序的

dic = {'a':'娃哈哈', 'b':'薯条', 'c':'胡辣汤'}
print(dic) # 最底层一定是无序的. 最底层是hash

from collections import OrderedDict
# 按照我们存储的顺序保存数据
od = OrderedDict({'b':'薯条','a':'娃哈哈', 'c':'胡辣汤'})
print(od)

    defaultdict: 可以给字典设置默认值, 当key不存在时, 直接获取默认值

from collections import defaultdict

d = defaultdict(list)  # {} # 参数位置给的内容必须是可调用的
d["周杰伦"] = "昆凌"
print(d["周杰伦"])  # 从字典中获取数据的时候. 如果这个key不存在. 去执行可执行的内容, 拿到的是一个空列表


# 以前的题目
lst= [11,22,33,44,55,66,77,88,99]
d = defaultdict(list)
for el in lst:
    if el < 66:
        d["key1"].append(el) # key1默认是不存在的. 但是可以拿key1. 一个空列表.
    else:
        d["key2"].append(el)
print(d)

# {'key1': [11, 22, 33, 44, 55], 'key2': [66, 77, 88, 99]})

三. time 时间模块(重点)

  1. 获取系统时间 time.time()  得到的结果是是时间戳(timestamp)   

    时间戳使用的1970年01月01日 00时00分00秒开始的到当前的秒数, 使用float 表示

  2. 格式化时间 time.strftime()   常用时间格式: %Y-%m-%d %H:%M:%S

while 1:
    s = time.strftime("%Y-%m-%d %H:%M:%S") #  使用频率最高
    print(s)
    time.sleep(1)
# 一秒一秒的打印时间

  3. 结构化时间  time.gmtime()  格林尼治时间  time.localtime() 当地时间

时间表示转换问题

# 从时间戳 -> 格式化时间
t = time.localtime(1542513992)  # 有时区问题   gmtime() 格林尼治时间.
print(t)
str_time = time.strftime("%Y-%m-%d %H:%M:%S", t)
print(str_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)
print(time.strftime("%Y年%m月%d日"))   # string format time

计算时差问题:

# 时间差  1小时30分
begin = "2018-11-14 16:30:00"
end = "2018-11-14 18:00:00"
# 用时间戳计算出时间差(秒)
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))


# 或者
begin = "2019-11-14 16:30:00"
end = "2018-11-14 18:00:00"
# 用时间戳计算出时间差(秒)
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)

# 转化成结构化时间
t = time.gmtime(diff_time_sec)  # 最好用格林尼治时间。 否则有时差
print(t)

print("时间差是%s年%s月 %s天 %s小时%s分钟" % (t.tm_year-1970, t.tm_mon-1, t.tm_mday-1,t.tm_hour, t.tm_min ))

四. random 模块
 

五. os 模块

 

 

 六. sys模块

原文地址:https://www.cnblogs.com/Knight-huang/p/9963492.html