一.collection 模块

python拥有一些内置的数据类型,比如 str,list.tuple.dict.set等

collection模块在这些内置的数据类型的基础上,提供了额外的数据类型:

  • namedtuple 具名元组 :
    •   生成可以使用名字来访问元素内容的元组
  • deque 双端队列:
    •   可以快速的从另外一侧追加和退出对象
  • Counter 计数器:
    •   主要用来计数
  • OrderedDict 有序字典:

    •   按照键值对插入的顺序排序,不是key本身的顺序
  • defaultdict 带有默认值的字典
    • 当我使用普通的字典时,用法一般是dict={},添加元素的只需要
      dict[key] =value,调用的时候也是如此,dict[key],
      但前提是key在字典里,如果不在字典里就会报错 这时defaultdict就能排上用场了,defaultdict的作用是在于,
      当字典里的key不存在但被查找时,返回的不是keyError而是一个默认值, defaultdict可以跟参数,参数可以是list、set、str,boor等等,
      作用是当key不存在时,返回的是参数的默认值,
      比如:
      list对应[ ],
      str对应的是空字符串,
      set对应set( ),
      int对应0
      boor对应False

1.namedtuple

# 想表示坐标点 x = 1, y = 2 的坐标 point
# 普通元组表示
point = (1,2)
print(point) # >>> (1,2) 无法辨别这是一个坐标点 """namedtuple 方法可以给元组命名"""
from collections import namedtuple point = namedtuple('坐标',['x','y','z']) # 第二个参数可以是可迭代带对象
# point = namedtuple('坐标','x y z') # 第二个参数也可以是字符串,但字符串之间要用空格隔开
p = point(5,2,1) # 注意: 传入的实参必须以定义是需要的参数个数相同
print(p) # >>> 坐标(x=5, y=2, z=1)
# print(point(5,2,1))
print(p.x) # >>> 5
print(p.y) # >>> 2
print(p.z) # >>> 1
# 可以单独打印出 传入是实参 # 例 定义扑克牌花色和大小
card = namedtuple('扑克牌','color number')
# card = namedtuple('扑克牌',['color','number'])
A = card('黑桃','A')
print(A) # >>> 扑克牌(color='黑桃', number='A')
print(A.color) # >>> 黑
print(A.number) # >>> A

2.deque

import queue
q = queue.Queue() # 生成队列对象
# put()方法 向队列中添加值,先加入的在前面
# get()方法 从队列中取值,从第一个开始取
q.put('one')
q.put('two')
q.put('three') print(q.get()) # >>> one
print(q.get()) # >>> two
print(q.get()) # >>> three print(q.get()) # 如果值取完了,程序会在原地等待,直到拿到值 '''双端队列''' from collections import deque
q = deque(['w','a','l'])
# wo = deque(('w','a','l'))
'''
append 在尾部添加
appendlift 在头部添加 pop 从尾部弹出
poplift 从头部弹出
'''
q.append(1)
q.appendleft(9)
print(q) # >>> deque([9, 'w', 'a', 'l', 1]) print(q.pop()) # >>> 1
print(q.popleft()) # >>> 9
print(q) # deque(['w', 'a', 'l'])

3.OrderedDict

d = dict([('a',1),('b',2),('c',3)])
print(d) # 字典的key是无序的
# print({i for i in d}) '''OrderedDict有序字典''' from collections import OrderedDict
oredr_d = OrderedDict([('a',1),('b',2),('c',3)])
print(oredr_d) # >>> OrderedDict([('a', 1), ('b', 2), ('c', 3)])
order = OrderedDict()
order['x'] = 1
order['z'] = 2
order['y'] = 3
print(order) # >>> OrderedDict([('x', 1), ('z', 2), ('y', 3)])
# print({i for i in order}) # >>> {'z', 'x', 'y'}
for i in order:
print(i) # 按key在字典中的顺序取出

4.defaultdict

from collections import defaultdict
values = [11, 22, 33,44,55,66,77,88,99,90]
d = defaultdict(list) # 默认后续字典中key对应的value是列表
for i in values:
if i > 66:
d['key1'].append(i)
else:
d['key2'].append(i)
print(d)
# defaultdict(<class 'list'>, {'key2': [11, 22, 33, 44, 55, 66], 'key1': [77, 88, 99, 90]}) my_dict1 = defaultdict(int)
print(my_dict1['xxx'])
print(my_dict1['yyy'])
# 值不存在 返回 int 的默认值 0 my_dict2 = defaultdict(bool)
print(my_dict2['kkk'])
# 值不存在 返回 bool 的默认值 False my_dict3 = defaultdict(tuple)
print(my_dict3['mmm'])
# 值不存在 返回 tuple 对应的默认值 () 空元组 my_dict4 = defaultdict(list)
print(my_dict3['www'])
# 值不存在 返回 list 对应的默认值 [] 空列表

5.Counter

# 统计:
colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']
result = {}
for color in colors:
if result.get(color)==None:
result[color]=1
else:
result[color]+=1
print (result)
# >>> {'red': 2, 'blue': 3, 'green': 1} from collections import Counter
colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']
c = Counter(colors)
print(c) # >>> Counter({'blue': 3, 'red': 2, 'green': 1})
print (dict(c)) # >>> {'red': 2, 'blue': 3, 'green': 1}

二.时间模块

  • import time
  •   time.time() 用于返回当前时间的时间戳(从1970年1月1日00时00分00秒到现在的浮点秒数)
  •   time.sleep(n) 让程序睡眠 n 秒
  •   time.strftime() 时间样式
  •         time.localtime() 格式化时间戳为本地时间
  • import datetime
  •         datetime.date.tody()  当前年月日
  •   datetime.datetime.today() 当前年月日时分秒

(******)

日期对象 = 日期对象 +/- timedelta对象
timedelta对象 = 日期对象 +/- 日期对象
print(time.strftime('%Y-%m-%d'))
print(time.strftime('%Y-%m-%d %H:%M:%S'))
print(time.strftime('%Y-%m-%d %X')) # %X等价于%H:%M:%S
print(time.strftime('%H:%M'))
print(time.strftime('%Y/%m')) print(time.localtime()) print(time.localtime(time.time()))
res = time.localtime(time.time())
# print(time.time())
print(time.mktime(res))
print(time.strftime('%Y-%m',time.localtime()))
print(time.strptime(time.strftime('%Y-%m',time.localtime()),'%Y-%m'))
print(datetime.date.today())  # date>>>:年月日
print(datetime.datetime.today()) # datetime>>>:年月日 时分秒
res = datetime.date.today()
res1 = datetime.datetime.today()
print(res.year)
print(res.month)
print(res.day)
print(res.weekday()) # 0-6表示星期 0表示周一 print(res.isoweekday()) # 1-7表示星期 7就是周日
current_time = datetime.date.today()  # 日期对象
timetel_t = datetime.timedelta(days=7) # timedelta对象
res1 = current_time+timetel_t # 日期对象 print(current_time - timetel_t)
print(res1-current_time) # 小练习 计算今天距离今年过生日还有多少天
birth = datetime.datetime(2019,12,21,8,8,8)
current_time = datetime.datetime.today()
print(birth-current_time) # UTC时间
dt_today = datetime.datetime.today()
dt_now = datetime.datetime.now()
dt_utcnow = datetime.datetime.utcnow()
print(dt_utcnow,dt_now,dt_today)

三.random随机模块

random.random()

  随机 0-1 之间的小数

random.randint()

  随机整数

random.choice()

  随机从可迭代对象中去一个数

random.shuffle()

  洗牌,打乱

print(random.random())  # 随机 0-1 之间的小数
print(random.randint(1,7)) # 随机 1-7 之间的整数,包含收尾
print(random.choice([1,2,3,4,5])) # 随机从列表中取一个数
print(random.choice((1,2,3,5,6,7))) # choice 的参数 需是可迭代对象
res = [1,5,2,7,9,6]
random.shuffle(res) # 洗牌,打乱
print(res)
up_res = chr(random.randint(65,90)) # 按ASCII码表随机取一个大写字母
print(up_res)
low_res = chr(random.randint(97,122)) # 按ASCII码表随机取一个小写字母
print(low_res)
# 生成随机验证码

"""
大写字母 小写字母 数字
5位数的随机验证码
chr
random.choice
封装成一个函数,用户想生成几位就生成几位
"""
def get_code(n):
code = ''
for i in range(n):
# 先生成随机的大写字母 小写字母 数字
upper_str = chr(random.randint(65,90))
lower_str = chr(random.randint(97,122))
random_int = str(random.randint(0,9))
# 从上面三个中随机选择一个作为随机验证码的某一位
code += random.choice([upper_str,lower_str,random_int])
return code
res = get_code(5)
print(res)

四 os模块

  os模块是与操作系统打交道

1 os.listdir()

  以列表的形式返回所指定文件下的所有文件夹和文件

print(os.listdir(r'D:\python视频\day16\代码\day16\老师们的作品'))
# >>> ['tank老师.txt', '冲老师.txt', '明老师.txt', '波老师.txt', '田老师.txt', '苍老师.txt']

2 os.path.dirname(__file__)

  获取当前所在py文件的文件夹路径(绝对路径)

BASE_DIR = os.path.dirname(__file__)
print(BASE_DIR) # >>> D:/python视频/day16/代码/day16

3 os.path.join()

  拼接绝对路径

join_dir = os.path.join(BASE_DIR,'老师们的作品')
print(join_dir) # >>> D:/python视频/day16/代码/day16\老师们的作品

4 os.mkdir()

  自动创建文件夹(在当前py文件的文件夹下创建)

5 os.path.exists()

  判断文件或文件夹 是否在指定的路径下

print(os.path.exists(r'D:\python脱产10期视频\day16\代码\day16\老师们的作品'))  # >>> True
print(os.path.exists(r'D:\python脱产10期视频\day16\代码\day16\老师们的作品\tank老师.txt')) # >>> True

6 os.path.isfile()

  只判断文件夹 是否在指定的路径下

print(os.path.isfile(r'D:\python脱产10期视频\day16\代码\day16\老师们的作品'))  # >>> False
print(os.path.isfile(r'D:\python脱产10期视频\day16\代码\day16\老师们的作品\tank老师.txt')) # >>> True

 7 os.path.rmdir()

  删除指定路径的文件夹 只删除空文件

os.rmdir(r'D:\Python项目\day16\老师们的作品')  # 只能删空文件夹

 8 os.getcwd()

  打印当前py文件所在的文件夹路径,与 dirname 相同

print(os.getcwd())# 打印当前py文件所在的文件夹路径
# >>> D:\python脱产10期视频\day16\代码\day16

9 os.chdir()

  切换到指定的文件夹路径

print(os.chdir(r'D:\python脱产10期视频\day16\代码\day16\老师们的作品'))  # 切换到指定的文件夹路径
print(os.getcwd()) # 与 chdir 和用,打印出所切换到的文件夹路径
# >>> D:\python视频\day16\代码\day16\老师们的作品

10 os.path.getsize()

  获取文件大小(字节数)

print(os.path.getsize(r'D:\python脱产10期视频\day16\代码\day16\老师们的作品\tank老师.txt'))  # 字节大小(个数)
with open(r'D:\python脱产10期视频\day16\代码\day16\老师们的作品\tank老师.txt',encoding='utf-8') as f:
print(len(f.read())) # 字符个数

五.sys模块

  sys模块是与python解释器打交道

1 sys.path.append() 

  将某个路径添加到系统环境变量中

BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# print(BASE_DIR)
sys.path.append(BASE_DIR)

 2 sys.platform

  电脑的系统配置

3 sys.version

  python 解释器版本

 4 sys.argv

  获取当前py文件的绝对路径,且以list形式返回

print(sys.argv)  # 命令行启动文件 可以做身份的验证
# ['D:/python脱产10期视频/day16/代码/day16/06 sys模块.py']

六.序列化模块

序列化:其他数据类型转成字符串的过程
反序列化:字符串转成其他数据类型

写入文件的数据必须是字符串,基于网络传输必须是二进制

1 json模块

  只支持的数据类型:

    字符串 列表 字典 整形 元组(转成列表) 布尔值

  优点:所有的语言都支持json格式

  缺点:支持的数据类型很少

dumps:序列化 将其他数据类型转成json格式的字符串
loads:反序列化 将json格式的字符串转换成其他数据类型
res = json.dumps(d)  # json格式的字符串 必须是双引号 >>>: '{"name": "jason"}'
print(res,type(res)) # >>> {"name": "jason"} <class 'str'>
res1 = json.loads(res) # 将 json 字符串格式的字典转成 字典
print(res1,type(res1)) # >>> {'name': 'jason'} <class 'dict'>
dump 针对文件操作 把字典转成json字符串并写入到文件
load 针对文件操作 把文件中以json字符串形式存的内容反序列化读出来
d = {"name":"json"} # 字典
with open('userinfo','w',encoding='utf-8') as f:
json.dump(d,f) # 转字符串形式的字典并自动写入文件 {"name": "json"} <class 'str'>
with open('userinfo','r',encoding='utf-8') as f:
res = json.load(f) # {'name': 'json'}<class 'dict'>
print(res,type(res))

2 pickle模块

  缺点:只支持python

  优点:python的所有的数据类型都支持

dumps 将数据序列化成二进制格式 ()可解码符内容)

loads 反序列化

d = {'name':'json'}
res = pickle.dumps(d) # 将对象直接转成二进制
print(pickle.dumps(d))
res1 = pickle.loads(res)
print(res1,type(res1))

dump 针对文件操作 把数据序列化成二进制并写入到文件

load 针对文件操作 把文件中以pickle形式存的二进制内容反序列化读出来

  用pickle操作文件的时候 文件的打开模式必须是b模式

with open('userinfo_1','wb') as f:
pickle.dump(d,f) with open('userinfo_1','rb') as f:
res = pickle.load(f)
print(res,type(res))

七.subprocess子进程

1.用户通过网络连接上了你的这台电脑
2.用户输入相应的命令 基于网络发送给了你这台电脑上某个程序
3.获取用户命令 里面subprocess执行该用户命令
4.将执行结果再基于网络发送给用户
这样就实现 用户远程操作你这台电脑的操作
while True:
cmd = input('cmd>>>:').strip()
import subprocess
obj = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
# print(obj)
print('正确命令返回的结果stdout',obj.stdout.read().decode('gbk'))
print('错误命令返回的提示信息stderr',obj.stderr.read().decode('gbk'))

collection,random,os,sys,序列化模块的更多相关文章

  1. 2019-7-18 collections,time,random,os,sys,序列化模块(json和pickle)应用

    一.collections模块 1.具名元组:namedtuple(生成可以使用名字来访问元素的tuple) 表示坐标点x为1  y为2的坐标 注意:第二个参数可以传可迭代对象,也可以传字符串,但是字 ...

  2. 7.18 collection time random os sys 序列化 subprocess 等模块

    collection模块 namedtuple 具名元组(重要) 应用场景1 # 具名元组 # 想表示坐标点x为1 y为2 z为5的坐标 from collections import namedtu ...

  3. python time,random,os,sys,序列化模块

    一.time模块 表示时间的三种方式 在Python中,通常有这三种方式来表示时间:时间戳.元组(struct_time).格式化的时间字符串: (1)时间戳(timestamp) :通常来说,时间戳 ...

  4. time,random,os,sys,序列化模块

    一.time模块 表示时间的三种方式 在Python中,通常有这三种方式来表示时间:时间戳.元组(struct_time).格式化的时间字符串: (1)时间戳(timestamp) :通常来说,时间戳 ...

  5. 常用模块random,time,os,sys,序列化模块

    一丶random模块 取随机数的模块 #导入random模块 import random #取随机小数: r = random.random() #取大于零且小于一之间的小数 print(r) #0. ...

  6. python之模块random,time,os,sys,序列化模块(json,pickle),collection

    引入:什么是模块:   一个模块就是一个包含了python定义和声明的文件,文件名就是模块名字加上.py的后缀. 但其实import加载的模块分为四个通用类型. 1.使用python编写的代码(.py ...

  7. python基础语法11 内置模块time,datatime,random,os,sys,hashlib模块

    time模块 在python的三种时间表现形式: 1.时间戳: 给电脑看的. - 自1970-01-01 00:00:00到当前时间,按秒计算,计算了多少秒. 2.格式化时间(Format Strin ...

  8. day19:常用模块(collections,time,random,os,sys)

    1,正则复习,re.S,这个在用的最多,re.M多行模式,这个主要改变^和$的行为,每一行都是新串开头,每个回车都是结尾.re.L 在Windows和linux里面对一些特殊字符有不一样的识别,re. ...

  9. 模块random+os+sys+json+subprocess

    模块random+os+sys+json+subprocess 1. random 模块   (产生一个随机值) import random 1 # 随机小数 2 print(random.rando ...

随机推荐

  1. why use reverse proxy in asp.net core

    开篇论点 Asp.net Core自带了Kestrel, 为什么我们还要使用诸如IIS.Apache或者Nginx来做反向代理呢? 原因分析 Kestrel用来承载Asp.net Core的动态内容是 ...

  2. Dockerfile指令的使用

    关于Dockerfile Dockerfile实际上就是一系列创建Docker镜像的脚本, 虽然可以通过命令行来执行, 但是那样繁琐而且容易出错. Dockerfile指令 FROM 他的意思是在创建 ...

  3. Properties类使用详解

    Java Properties类使用详解   概述 Properties 继承于 Hashtable.表示一个持久的属性集,属性列表以key-value的形式存在,key和value都是字符串. Pr ...

  4. Spring Boot 入门(八):集成RabbitMQ消息队列

    本片文章续<Spring Boot 入门(七):集成 swagger2>,关于RabbitMQ的介绍请参考<java基础(六):RabbitMQ 入门> 1.增加依赖 < ...

  5. jmu-Java-02基本语法-04-动态数组

    题目: 根据输入的n,打印n行乘法口诀表.需要使用二维字符串数组存储乘法口诀表的每一项,比如存放1*1=1.为了保证程序中使用了二维数组,需在打印完乘法口诀表后使用Arrays.deepToStrin ...

  6. DevExtreme学习笔记(一) DataGrid中js分析

    1.overviewjs采用 $(function() { $("#gridContainer").dxDataGrid({ dataSource: { store: { type ...

  7. Eclipse下使用Maven创建项目出现的archetype错误,记,转

    记自:http://blog.csdn.net/ZhuboSun/article/details/50099635 [1]出现的错误提示: Unable to create project from ...

  8. cocos-js 精灵移动转圈

    cc.Class({ extends: cc.Component, properties: { carModel: { default: null, type: cc.Sprite }, bgMode ...

  9. Python面向对象Day1

    一.面向对象初始 面向过程变成属于流水式 面向对象是一种思想 结构上理解面向对象:两部分 class A: # 类 name = '小明' # 静态属性,静态变量,静态字段,或者属性.变量.字段 de ...

  10. 在Linux中安装ASPNET.Core3.0运行时

    # 以下示例适用于x64位runtime v3.0.0 mkdir /runtimes cd /runtimes wget https://download.visualstudio.microsof ...