巨蟒python全栈开发-第22天 内置常用模块1

一.今日主要内容

1.简单了解模块
你写的每一个py文件都是一个模块

数据结构(队列,栈(重点))
还有一些我们一直在使用的模块
buildins 内置模块.print,input

random 主要和随机相关的内容
random() 随机小数
uninform(a,b) 随机小数

randint(a,b) 随机整数

choice() 随机选择一个
sample() 随机选择多个

shuffle() 打乱

2.Collections(很多人用同一个东西,这时候就用到了栈,未来学习并发可能用到)
(1) Counter 计数器
(2) defaultdict 默认值字典
(3) OrderedDict 有序字典

#python的大小写,各有不同,就是有很多人写的原因

数据结构(队列,栈(重点))
栈(list就是个栈):先进后出(后来居上)
Stack

#list
#lst.append()
#pop()

队列(Queue):先进先出(排的队就叫队列)
#Queue
3.Time模块
时间有三种:(金融项目对时间是很敏感的)
结构化时间: gmtime() localtime()
时间戳: time.time() time.mktime()
格式化时间: time.strftime() time.strptime()

时间转化:(任何转化必须经过结构化时间,这个是中间件)
数字=>字符串(2018-12-12 12:12:12):
struct_time=time.localtime(数字)
str=time.strftime('格式',struct_time) #格式:strftime(format,t)

字符串=>数字:
struct_time=time.strptime(字符串,'格式) #格式:strptime(string,format)
time.mktime(t)

4.functools
wraps #给装饰器中的inner改名字
偏函数 #把函数的参数固定
reduce: #归纳 #回收(map是往外边发,映射)

二.今日内容大纲

1.random

2.collections

3.栈和队列,双向队列

4.time

5.functools

三.今日内容详解

1.random

(1)

两种导入的了解
从某一个大的集合,导入集合中的某个小功能

from xxx import xxxx
from 老男孩 import alex #导入一个具体的功能
import 老男孩 #导入整个模块
import random
print(random.randint(10,20))    #随机整数包括10和20
from  random import  randint
print(randint(10,20))

(2)

一切随机数的根
import random
print(random.random())
python中所有随机数的根,随机小数0-1

(3)

import random
print(random.uniform(10-20))#10-20的随机小数
#思考:?是否包括10和20

(4)

import random
lst=['宝浪','宝宝','宝强','包拯']
random.shuffle(lst) #随机打乱顺序
print(lst)
#应用:洗牌

(5)

#从列表中随机选择一个,
import random
print(random.choice(['林志玲','胡一菲','王昭君','貂蝉','结衣','艾米']))

(6)

import random
print(random.sample(['林志玲','胡一菲','王昭君','貂蝉','结衣','艾米'],3))
'''
#结果:
貂蝉  #从列表中随机选择一个
['结衣', '王昭君', '胡一菲']    #从列表中随机返回三个返回,返回的形式是列表
'''

2.collections
(1)

from  collections import  Counter
print(Counter('宝宝今年特别喜欢王宝强'))#计数
#计算每个字符出现的次数
#结果:Counter({'宝': 3, '今': 1, '年': 1, '特': 1, '别': 1, '喜': 1, '欢': 1, '王': 1, '强': 1})

(2)

from  collections import  Counter
lst=['jay','jay','jay','宝宝','宝宝','胡辣汤','上官婉儿','上官婉儿']
c=Counter(lst)  #类似于字典

print(c.get('宝宝'))  #结果:2  检测'宝宝'出现的次数
print(c)
#结果:Counter({'jay': 3, '宝宝': 2, '上官婉儿': 2, '胡辣汤': 1})

(3)Counter内字典

from  collections import  Counter
dic={'a':'哈哈','b':'哈哈','c':'车牌'}
c=Counter(dic)
print(c)
#结果:Counter({'c': '车牌', 'a': '哈哈', 'b': '哈哈'})

(4)Counter内字典的值

from  collections import  Counter
dic={'a':'哈哈','b':'哈哈','c':'车牌'}
c=Counter(dic.values())
print(c)
#结果:Counter({'哈哈': 2, '车牌': 1})

(5)

#默认值字典,了解就行
from  collections import defaultdict
dd=defaultdict(lambda:'胡辣汤')    #callable 可调用的 字典是空的

print(dd['张无忌'])    #从字典向外拿数据,字典是空的.key:callable()
print(dd['宝宝'])     #这里的[]和get()不是一回事儿
print(dd)

'''
结果:
    胡辣汤
    胡辣汤
    defaultdict(<function <lambda> at 0x0000020695841E18>, {'张无忌': '胡辣汤', '宝宝': '胡辣汤'})
'''

(6)

#顺序字典
from collections import OrderedDict       #现在字典用的就是OrderDict

dic=OrderedDict()   #有序字典  #按照存储顺序排列
print(dic)
dic['b']='哈哈'
dic['a']='呵呵'
print(dic)
print(dic['a'])
print(dic.get('a'))
print(dic.values())
'''
# 结果:
    OrderedDict()
    OrderedDict([('b', '哈哈'), ('a', '呵呵')])
                    以前用的多,现在用的比较少了,按照存储的顺序进行排列
    呵呵
    呵呵
    odict_values(['哈哈', '呵呵'])
'''

(7)

#目的是用,不是打印
class Person:
    def __str__(self):
        print('嘻嘻')
        return '嘎嘎'
p=Person()
print(p)
'''
结果:
    嘻嘻
    嘎嘎
'''

3.栈和队列,双向队列(重磅知识点!!!)

(1)

#
#特点:先进后出
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) #放元素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())

'''
结果:
    说的话
    刚刚
    你
    记得
    你好
    宝宝
'''
#出栈是先进后出

# 老师傅蒸馒头,消费者和生产者模型

(2)

在队列中,一个一个出来,队列比栈还重要(用的频率非常高)
从上往下跑到底的
DDOS攻击 &CC攻击
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())

(3)

from collections import  deque
d=deque()  #创建双向队列
d.append('宝宝')
d.append('no')      #在右侧添加
d.append('way')
d.append('哈哈')
d.appendleft('娃哈哈')     #在左边添加
d.appendleft('爽歪歪')     #在左边添加
d.appendleft('优酸乳')     #在左边添加
#(思维一)
# print(d.popleft())      #从左边拿数据
# print(d.popleft())      #从左边拿数据
# print(d.popleft())      #从左边拿数据
# print(d.popleft())      #从左边拿数据
# print(d.popleft())      #从左边拿数据
# print(d.popleft())      #从左边拿数据
# print(d.popleft())      #从左边拿数据
#(思维二)
print(d.pop())        #从右边拿数据
print(d.pop())        #从右边拿数据
print(d.pop())        #从右边拿数据
print(d.pop())        #从右边拿数据
print(d.popleft())      #从左边拿数据
print(d.popleft())      #从左边拿数据
print(d.popleft())      #从左边拿数据
目前,我们先了解(圆)
双向循环队列(最好用的) (圆,双向)//圆桌谈判 C语言 非常节省内存
双向队列 (圆,单向)#优点:节省内存

4.time

(1)

import time
#时间戳:从1970-01-01 00:00:00开始计算,未来存储的时候用的是时间戳
#格林尼治,0度经线经过的,中国晚8个小时
print(time.time())  #1545793561.4665143

#记住,这个以后能用到,用来显示的
print(time.strftime('%Y-%m-%d %H:%M:%S'))  #格式化时间 str_float_time
print(time.strftime('%Y/%m/%d %H:%M:%S'))  #格式化时间 str_float_time
print(time.strftime('%Y-%m-%d %X'))  #格式化时间 str_float_time
print(time.localtime())
#python里边的时间
t=time.localtime()
print(t.tm_year)    #2018
print(t.tm_mon)     #12
print(t.tm_min)     #40

'''
结果:
2018-12-26 21:21:54
2018/12/26 21:21:54
2018-12-26 21:21:54
time.struct_time(tm_year=2018, tm_mon=12, tm_mday=26, 
tm_hour=21, tm_min=21, tm_sec=54, tm_wday=2, tm_yday=360, 
tm_isdst=0)
'''

(2)

import time
#重点:  公式:strftime(format,t)    strptime(string,format)
#数据库里存储一个数字,把它还原成我们的格式化时间
a=1888888888
#先把这个时间戳转化成python中的结构化时间
t=time.localtime(a)
# print(t)

# #把一个结构化时间转化成格式化时间
s=time.strftime("%Y-%m-%d %H:%M:%S",t)
print(s)
'''
结果:
time.struct_time(tm_year=2029, tm_mon=11, tm_mday=9, tm_hour=11, tm_min=21, tm_sec=28, tm_wday=4, tm_yday=313, tm_isdst=0)
2029-11-09 11:21:28
'''

(3)

import time
# 让用户输入一个时间,然后把时间转化成时间戳
str_t=input('请输入一个时间:')     #2018-01-02 12:21:02
#把字符串转化成结构化时间
t=time.strptime(str_t,'%Y-%m-%d %H:%M:%S')
#转化成时间戳
print(time.mktime(t))               #1514866862.0

#1970-01-01 08:00:00        #这个我们计算的结果是北京时间,所以,这个时间是北京当地时间,而不是英国时间
#结果:0.0

5.functools

(1)

#回忆装饰器
def wrapper(fn):
    def inner(*args,**kwargs):
        print('')
        ret=fn(*args,**kwargs)
        print('')
        return ret
    return inner

@wrapper  #func=wrapper(func)
def func():
    print('哈哈哈')
print(func.__name__)
#注意,加了装饰器这个结果是inner
#不加装饰器这个结果是func

#flask会有具体的讲解,具体会用到

(2)wraps

from functools import wraps     #可以改变一个函数的名字,注释
def wrapper(fn):
    @wraps(fn)      #伪装成fn参数的样子(伪装玩法),结果显示的却是func
                    #把inner的名字改变成原来的func
    def inner(*args,**kwargs):
        print('')
        ret=fn(*args,**kwargs)
        print('')
        return ret
    return inner

@wrapper  #func=wrapper(func)
def func():
    print('哈哈哈')
s=func()
print(s)
print(func.__name__)  #func

(3)map回忆

#map管杀不管埋
#map映射       reduce总结,归纳

print(list(map(lambda x:x**2,[i for i in range(10)])))

#结果:[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

(4)

#会把我们每一个数据交给func去执行,把默认值作为第一个参数传递给函数
#第二个参数就是你这个序列中的第一个数据
#接下来,把刚才返回的结果作为第一个参数传递给a
#继续把刚才的结果给第一个参数,把第三个数据传递给b

#reduce参数(function,sequence,默认值)   #函数,序列

from functools import reduce
def func(a,b):
    return a+b      #累加,还可以做累乘    #0+1...
ret=reduce(func,[1,4,7,2,5,8,3,6,9],0)
#工作流程
print(ret)              #45

from functools import reduce
print(reduce(lambda a,b:a+b,[1,4,7,2,5,8,3,6,9],0))     #45
print(reduce(lambda a,b:a+b,[i for i in range(101)]))   #5050

#工作流程:
#func(func(func(0,1),4),7)

(5)偏函数

#partial 偏函数
#固定函数中某些参数的值

from functools import partial
def chi(zhushi,fushi):
    print(zhushi,fushi)
chi2=partial(chi,fushi='辣鸡爪')  #核心语句
chi2('大米饭')
chi2('小米饭')
chi2('紫米饭')
chi2('黄米饭')
chi2('软米饭')
chi2('大米饭')

'''
结果:
大米饭 辣鸡爪
小米饭 辣鸡爪
紫米饭 辣鸡爪
黄米饭 辣鸡爪
软米饭 辣鸡爪
大米饭 辣鸡爪
'''
from functools import partial

def chi(zhushi,fushi):
    print(zhushi,fushi)

chi2=partial(chi,fushi='辣鸡爪')
# chi2('宝宝','胡辣汤')        #报错
chi2('宝宝',fushi='胡辣汤')        #不报错,结果是:宝宝 胡辣汤
chi('宝宝','胡辣汤')                 #原来的也是可以用的,结果是:宝宝 胡辣汤

回忆之前学习的,回归基础,当一切回归到了基础,事情会变得那么的美好.

猜你喜欢

转载自www.cnblogs.com/studybrother/p/10182666.html
今日推荐