一.模块的简单认识
什么是模块. 模块就是我们把装有特定功能的代码进行归类的结果. 从代码编写的单位来看我们的程序, 从小到大的顺序: 一条代码 < 语句句块 < 代码块(函数, 类) < 模块. 我们目前写的所有的py文件都是模块.
二.常用模块
1.random模块
2.cllections模块
3.time模块
4.os模块
5.sys模块
random模块
(1)random 随机小数0-1 (2)randint 随机整数 (3)uniform 随机小数
(4)shuffle 打乱顺序 (5)choice 随机选一个 (6)sample 随机选多个
import random # print(random.randint(1,20)) #整数随机数 # print(random.random()) #python中所有随机数的根 随机小数0-1 # print(random.uniform(1,2)) #随机小数 lst =['1','2','3','4','5'] # random.shuffle(lst) #列表打乱顺序 # print(lst) print(random.choice(['1','2','3','4','5'])) # 列表中随机选一个 print(random.sample(['1','2','3','4','5'],3)) #列表中随机取几个
collection模块
1.Counter 迭代后计数
from collections import Counter
Counter({'宝': 3, '今': 1, '年': 1, '特': 1, '别': 1, '喜': 1, '欢': 1, '王': 1, '强': 1})
print(Counter('宝宝今年特别喜欢王宝强'))
COunter() 迭代后计数
lst =['1','1','1','2','3','4','4','5','4']
print(Counter(lst)) #Counter({'1': 3, '4': 3, '2': 1, '3': 1, '5': 1})
c = Counter(lst)
print(c.get('1'))
2.defaultdict 默认值字典
from collections import defaultdict # 默认值字典 dd = defaultdict(lambda: '机器人') # callable 可调用的, 字典是空的 print(dd["大雄"]) # 从字典向外拿数据. 字典是空的. key:callable() print(dd["宝宝"]) # 这里的[] 和get()不是一回事儿 print(dd)
3,OrderedDict 有序字典
from collections import OrderedDict dic = OrderedDict() # 有序字典 dic["b"] = "哈哈" dic['a'] = "呵呵" print(dic)
#OrderedDict([('b', '哈哈'), ('a', '呵呵')])
数据结构(队列,栈)
栈 特点,先进后出
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('满了')
self.lst.insert(self.top,el) #放元素
self.top +=1 #栈顶指针往上走一位
#出栈
def pop(self):
if self.top == 0:
raise StackEmptyException ('空了')
self.top -= 1
el = self.lst[self.top]
return el
s= Stack(6)
s.push('1')
s.push('2')
s.push('3')
s.push('4')
s.push('5')
s.push('6')
s.pop()
s.pop()
s.pop()
s.pop()
s.pop()
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()) #1
print(q.get()) #2
print(q.get()) #3
print(q.get()) #4
print(q.get()) #5
双向队列
from collections import deque
d = deque() # 创建双向队列
d.append("宝宝") # 在右侧添加
d.append("no")
d.append("way")
d.append("哈哈")
d.appendleft("娃哈哈") # 在左边添加
d.appendleft("爽歪歪")
d.appendleft("优酸乳")
print(d.pop()) # 从右边拿数据
print(d.pop()) # 从右边拿数据
print(d.pop()) # 从右边拿数据
print(d.pop()) # 从右边拿数据
print(d.popleft()) # 从左边拿数据
print(d.popleft()) # 从左边拿数据
print(d.popleft()) # 从左边拿数据
time模块
.