day 22 内置的模块

1.简单的理解模块
写的每一个py文件都是一个模块,还有一些是我们一直在使用的模块.
buildins: 内置模块. print, input
random 主要是和随机相关的内容:
        random()  随机小数  ,是python中所有随机数的根, 随机小数0-1
        uniform(a,b)  a - b之间的随机小数
       randint(a,b)   随机整数
      choice()  随机选择一个
       sample() 随机选择多个
       shuffle() 打乱
# from xxx import xxxx
# from 老男孩 import alex # 导入一个具体的功能
# import 老男孩 # 导入整个模块
 
 
# import random
# print(random.randint(10,20))
#
# from random import randint
# print(randint(10,20))
import random
print(random.randint(10,20)) # 随机整数
print(random.random()) # python中所有随机数的根 随机小数 0-1
 
print(random.uniform(10,20)) # 10-20的随机小数
lst = ["宝宝", "宝强", "宝浪", "包拯"]
random.shuffle(lst)  # 随机打乱顺序
print(lst)
 
从列表中随机选择一个
print(random.choice(["林志玲", "刘一菲", "王昭君", "艾米", "宝宝"]))
print(random.sample(["林志玲", "刘一菲", "王昭君", "艾米", "宝宝"], 3))
2.Collections
     1. Counter  计数器
     2. defaultdict   默认值字典
     3. orderedDict  有序字典(了解一下)
     4. deque  双向队列
from collections import Counter
 
print(Counter("宝宝今年特别喜欢王宝强")) # 计数
###Counter({'宝': 3, '今': 1, '年': 1, '特': 1, '别': 1, '喜': 1, '欢': 1, '王': 1, '强': 1})
lst = ["jay",'jay',"jay","宝宝","宝宝", "胡辣汤", "上官婉儿", "上官婉儿"]
print(Counter(lst))
dic = {"a":"哈哈", "b":"哈哈", "c":"车牌"}
c = Counter(dic.values())
print(c)
   
from collections import defaultdict
 
# 默认值字典
dd = defaultdict(lambda: 0) # callable 可调用的, 字典是空的
 
print(dd["张无忌"]) # 从字典向外拿数据. 字典是空的. key:callable()
print(dd["宝宝"]) # 这里的[] 和get()不是一回事儿
print(dd)
 
 
from collections import OrderedDict
 
dic = OrderedDict()  # 有序字典
dic["b"] = "哈哈"
dic['a'] = "呵呵"
print(dic)
print(dic.get("a"))
print(dic.values())
print(dic["a"])
 
数据结构(队列,栈(重点))
        栈: 先进后出    Stack
        队列: 先进先出   Queue
# 栈
# 特点: 先进后出
class StackFullException(Exception):
    pass
 
class StackEmptyException(Exception):
    pass
 
class Stack:
 
    def __init__(self, size):
        self.size = size
        self.lst = [] # 存放数据的列表
        self.top = 0 # 栈顶指针
 
    # 入栈
    def push(self, el):
        if self.top >= self.size:
            raise StackFullException("your stack is full!!!!!")
        self.lst.insert(self.top, el) # 放元素
        self.top += 1 # 栈顶指针向上移动一下
 
    # 出栈
    def pop(self):
        if self.top == 0:
            raise StackEmptyException("your stack is empty!!!!!")
        self.top-=1
        el = self.lst[self.top]
        return el
 
s = Stack(6)
s.push("宝宝")
s.push("我还")
s.push("记得")
s.push("你")
s.push("刚刚")
s.push("说的话")
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop())
import queue
q = queue.Queue()
q.put("李嘉诚1")
q.put("李嘉诚2")
q.put("李嘉诚3")
q.put("李嘉诚4")
q.put("李嘉诚5")
 
print(q.get())
print(q.get())
print(q.get())
print(q.get())
print(q.get())
 
 
from collections import deque
 
d = deque() # 创建双向队列
d.append("宝宝") #  在右侧添加
d.append("no")
d.append("way")
d.append("哈哈")
d.appendleft("娃哈哈") # 在左边添加
d.appendleft("爽歪歪")
d.appendleft("优酸乳")
3.Time 模块
    时间有三种:
         结构化时间:  gmtime()    localtime()
        时间戳  :   time.time()    time.mktime()
时间戳: 从1970-01-01 00:00:00开始计算. 未来存储的时候用是时间戳,使用float来表示
        格式化时间:  time.strftime()    time.strptime()
%Y-%m-%d %H:%M:%S
日期格式化的标准:
%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 当前时区的名称 
%% %号本身
  时间转化:
    数字  -> 格式化
   struct_time = time.localtime(数字)    ##结构化时间
   str= time.strftime('格式', struct_time)   ##格式化时间
   格式化  -> 数字
  struct_time = time.strptime(字符串,'格式')  ##转化成结构时间
  num =time.mktime(struct_time)    ##转化成时间戳
import time
 
时间戳: 从1970-01-01 00:00:00开始计算. 未来存储的时候用是时间戳
print(time.time())
格式化时间
print(time.strftime("%Y-%m-%d %H:%M:%S"))  # 用来显示的  # 2018-01-02 12:38:56
print(time.strftime("%Y-%m-%d %H:%M:%S   %Z"))  # ?D1¨²¡À¨º¡Á?¨º¡À??
 
结构化时间(python的时间)
print(time.localtime())
t = time.localtime()
print(t.tm_year)
print(t.tm_mon)
print(t.tm_min)
 
import time
重点:
# 数据库里存储一个数字. 把它还原成我们的格式化时间
a = 0
# 先把这个时间戳转化成python中的结构化时间
# t = time.localtime(a) # 本地化的东八区的时间
t = time.gmtime(a) # 格林尼治时间
# 把一个结构化时间转化成格式化时间
s = time.strftime("%Y-%m-%d %H:%M:%S", t)
print(s)
让用户输入一个时间,把这个时间转化成时间戳
import time
user_input = input("请输入一个时间:")
# 把用户输入的字符串转化成结构化时间
struct_time = time.strptime(user_input, "%Y-%m-%d %H:%M:%S") # p: parse
# 转化成时间戳
num = time.mktime(struct_time)
print(num)
4.functools
     wraps  给装饰器中的inner改名字
     reduce   归纳   和map 映射对应
    偏函数     把函数的参数固定
# 回忆装饰器
 
from functools import wraps # 可以改变一个函数的名字, 注释...
 
def wrapper(fn):
    @wraps(fn)  # 把inner的名字改变成原来的func
    def inner(*args, **kwargs):
        print("前")
        ret = fn(*args, **kwargs)
        print("后")
        return ret
 
    return inner
 
@wrapper # func = wrapper(func)
def func():
    print('哈哈哈')
 
print(func.__name__) # func
map 映射  reduce 归纳
print(list(map(lambda x: x**2, [i for i in range(10)])))
 
from functools import reduce
 
def func(a, b):
    return a + b # 0+1 +4 +7+2+5+8+3+6+9 # 累加
 
# 会把我们每一个数据交给func去执行, 把默认值作为第一个参数传递给函数
# 第二个参数就是你这个序列中的第一个数据
# 接下来. 把刚才返回的结果作为第一个参数传递个a
# 继续吧刚才的结果给第一个参数. 把第三个数据传递给b
ret = reduce(func, [1,4,7,2,5,8,3,6,9])
# 工作流程
# func(func(func(0, 1),4),7)
# print(ret)
# print(reduce(lambda x, y:x + y, [i for i in range(101)]))
偏函数  吧函数的参数固定
from functools import partial
 
def chi(zhushi, fushi):
    print(zhushi, fushi)
 
# 固定函数中某些参数的值
chi2 = partial(chi, fushi="辣鸡爪")
# chi2("大米饭")
# chi2("小米饭")
# chi2("黑米饭")
# chi2("黄米饭")
# chi2("紫米饭")
# chi2("糯米饭")
 
posted @ 2018-12-27 20:52  杨洪涛  阅读(134)  评论(0编辑  收藏  举报