一、collection模块
1.nametuple(具名元组)
生成可以使用名字来访问元素内容的tuple
2.例子:
(1)表示坐标
from collections import namedtuple
point = namedtuple('坐标',['x','y','z']) # 第二个参数既可以传可迭代对象
point = namedtuple('坐标','x y z') # 也可以传字符串 但是字符串之间以空格隔开
p = point(1,2,5) # 注意元素的个数必须跟namedtuple第二个参数里面的值数量一致
print(p)
print(p.x)
print(p.y)
print(p.z)
注意:nametuple第二个参数既可以传可迭代对象,也可以传字符串,字符串之间以空格隔开
元素的个数必须跟nametuple第二个参数里面的值数量一致
(2)扑克牌
from collections import namedtuple
card = namedtuple('扑克牌','color number')
# card1 = namedtuple('扑克牌',['color','number'])
A = card('♠','A') # 扑克牌(color='♠', number='A')
print(A)
print(A.color)
print(A.number)
2.deque:是为了高效实现插入和删除操作的双向列表,适用于队列和栈
队列:先进先出(FIFO first in first out)
import queue
q = queue.Queue() # 生成队列对象
q.put('first') # 往队列中添加值
q.put('second')
q.put('third')
print(q.get()) # 朝队列要值
print(q.get())
print(q.get())
print(q.get()) # 如果队列中的值取完了 程序会在原地等待 直到从队列中拿到值才停止
deque双端队列除了实现list的append()和pop()外,还支持appendleft()和popleft(),这样就可以非常高效地往头部添加或删除元素
from collections import deque
q = deque(['a','b','c'])
q.append(1)
q.appendleft(2)
q.insert(0,'哈哈哈') # 特殊点:双端队列可以根据索引在任意位置插值
print(q.pop()) # 1
print(q.popleft()) # 哈哈哈
print(q.popleft()) # 2
注意:队列不应该支持任意位置插值,只能在首尾插值(不能插队)
双端队列可以根据索引在任意位置插值
3.OrderedDict:有序字典
from collections import OrderedDict
d = dict([('a', 1), ('b', 2), ('c', 3)])
print(d) # dict的Key是无序的 {'a': 1, 'c': 3, 'b': 2}
od = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
print(od) # OrderedDict的Key是有序的 OrderedDict([('a', 1), ('b', 2), ('c', 3)])
注意:OrderedDict的Key会按照插入的顺序排列,不是Key本身排序:
from collections import OrderedDict
od = OrderedDict()
od['z'] = 1
od['y'] = 2
od['x'] = 3
print(od.keys()) # 按照插入的Key的顺序返回 ['z', 'y', 'x']
4.defaultdict:带有默认值的字典
from collections import defaultdict
values = [11, 22, 33,44,55,66,77,88,99,90]
my_dict = defaultdict(list) # 后续该字典中新建的key对应的value默认就是列表
print(my_dict['aaa']) # []
for value in values:
if value>66:
my_dict['k1'].append(value)
else:
my_dict['k2'].append(value)
print(my_dict)
# defaultdict(<class 'list'>, {'aaa': [], 'k2': [11, 22, 33, 44, 55, 66], 'k1': [77, 88, 99, 90]})
from collections import defaultdict
my_dict1 = defaultdict(int) # 后续该字典中新建的key对应的value默认就是整型
print(my_dict1['xxx']) # 0
my_dict2 = defaultdict(bool) # 后续该字典中新建的key对应的value默认就是布尔值
print(my_dict2['kkk']) # False
my_dict3 = defaultdict(tuple) # 后续该字典中新建的key对应的value默认就是元组
print(my_dict3['mmm']) # ()
5.counter:计数器,用来跟踪值出现的次数。它是一个无序的容器类型,以字典的键值对形式存储,其中元素作为key,其计数作为value。
from collections import Counter
s = 'abcdeabcdabcaba'
res = Counter(s)
print(res) # Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})
二、time与datetime模块
1.表示时间的三种方式
(1)时间戳:时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。我们运行“type(time.time())”,返回的是float类型。计算机能够识别的时间
(2)格式化时间(用来展示给人看的):‘1999-12-06’
python中时间日期格式化符号
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIn5GcucTO0EDM5cDN00yN4IzNzMDN4EDOxcDM5EDMy0COyMjN5YTMvw1NwkTMwIzLchjMzYTO2EzLcd2bsJ2Lc12bj5ycn9Gbi52YugTMwIzZtl2Lc9CX6MHc0RHaiojIsJye.png)
(3)结构化时间:操作时间的
2.时间字符串
import time
print(time.strftime('%Y-%m-%d')) # 2019-07-18
print(time.strftime('%Y-%m-%d %H:%M:%S')) # 2019-07-18 18:47:04
print(time.strftime('%Y-%m-%d %X')) # %X等价于%H:%M:%S
print(time.strftime('%H:%M')) # 18:47
print(time.strftime('%Y/%m')) # 2019/07
3.时间元组:localtime将一个时间戳转换为当前时区的struct_time
import time
print(time.localtime()) # time.struct_time(tm_year=2019, tm_mon=7, tm_mday=18, tm_hour=18, tm_min=55, tm_sec=26, tm_wday=3, tm_yday=199, tm_isdst=0)
print(time.strftime('%Y-%m',time.localtime())) # 2019-07
4.结构化时间--时间戳(mktime)
import time
time_tuple = time.localtime(1500000000)
res = time.mktime(time_tuple)
print(res) # 1500000000.0
5.结构化时间--字符串时间(strftime)
import time
res = time.strftime("%Y-%m-%d %X")
print(res) # 2019-07-18 19:03:39
res1 = time.strftime("%Y-%m-%d",time.localtime(1563447870.4117234))
print(res1) # 2019-07-18
6.字符串时间--结构化时间(strptime)
import time
print(time.strptime(time.strftime('%Y-%m',time.localtime()),'%Y-%m'))
# time.struct_time(tm_year=2019, tm_mon=7, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=182, tm_isdst=-1)
7.获取年月日
import datetime
now_date = datetime.date.today()
print(now_date) # 2019-07-18
8.获取年月日时分秒
import datetime
now_time = datetime.datetime.today()
print(now_time) # 2019-07-18 19:10:21.040734
import datetime
res = datetime.datetime.today()
print(res.year) # 获取年份
print(res.month) # 获取月份
print(res.day) # 获取日期
print(res.weekday()) # 0-6表示星期 0表示周一
print(res.isoweekday()) # 1-7表示星期 7就是周日
9.日期对象 = 日期对象 +/- timedelta对象
timedelta对象 = 日期对象 +/- 日期对象
import datetime
current_time = datetime.date.today() # 日期对象
timetel_t = datetime.timedelta(days=7) # timedelta对象
res1 = current_time+timetel_t # 日期对象
print(current_time - timetel_t) # 2019-07-11
print(res1-current_time) # 7 days, 0:00:00
例子:计算今天距离今年过生日还有多少天
import datetime
birth = datetime.datetime(2020,1,17,8,8,8)
current_time = datetime.datetime.today()
print(birth-current_time)
UTC时间(总结年月日时分秒及时区问题)
import datetime
dt_today = datetime.datetime.today()
dt_now = datetime.datetime.now()
dt_utcnow = datetime.datetime.utcnow()
print(dt_utcnow,dt_now,dt_today)
# 2019-07-18 11:20:25.553920 2019-07-18 19:20:25.553920 2019-07-18 19:20:25.553921
三、random模块
1.随机小数
import random
res = random.random() # 大于0且小于1之间的小数
2.随机整数
import random
random.randint(1,5) # 大于等于1且小于等于5之间的整数
3.随机选择一个返回
import random
random.choice([1,'23',[4,5]]) # #1或者23或者[4,5]
4.打乱列表顺序(洗牌)
import random
res = [1,2,3,4,5,6]
random.shuffle(res) # 洗牌
5.生成随机验证码
"""
大写字母 小写字母 数字
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(4)
print(res)
四、os模块
1.os模块:跟操作系统打交道的模块
2.需要掌握的方法:
(1)os.path.dirname(path):返回path的目录。
(2)os.path.join(path1[,path2[,...]]):将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
(3)os.listdir('dirname'):列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
(4)os.mkdir('dirname'):生成单级目录
(5)os.path.exists(path):如果path存在,返回True;如果path不存在,返回False
(6)os.path.isfile(path):如果path是一个存在的文件,返回True。否则返回False
(7)os.rmdir('dirname'):删除单级空目录,若目录不为空则无法删除,报错
(8)os.getcwd():获取当前工作目录,即当前python脚本工作的目录路径
(9)os.chdir("dirname"):改变当前脚本工作目录
(10)os.path.getsize(path):返回path的大小(字节大小和字符大小)
3.了解部分
os.makedirs('dirname1/dirname2') 可生成多层递归目录
os.removedirs('dirname1') 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
os.remove() 删除一个文件
os.rename("oldname","newname") 重命名文件/目录
os.stat('path/filename') 获取文件/目录信息
os.system("bash command") 运行shell命令,直接显示
os.popen("bash command).read() 运行shell命令,获取执行结果
os.path.abspath(path) 返回path规范化的绝对路径
os.path.split(path) 将path分割成目录和文件名二元组返回
os.path.basename(path) 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
os.path.isabs(path) 如果path是绝对路径,返回True
os.path.isdir(path) 如果path是一个存在的目录,则返回True。否则返回False
os.path.getatime(path) 返回path所指向的文件或者目录的最后访问时间
os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间
五、sys模块
1.sys模块是与python解释器交互的一个接口
2.常用方法:
(1)sys.argv:命令行启动文件 可以做身份的验证
(2)sys.path:返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
(3)sys.exit(n):退出程序,正常退出时exit(0),错误退出sys.exit(1)
(4)sys.version:获取Python解释程序的版本信息
(5)sys.platform:返回操作系统平台名称
3.例子:用户身份验证
import sys
print(sys.argv) # 命令行启动文件 可以做身份的验证
if len(sys.argv) <= 1:
print('请输入用户名和密码')
else:
username = sys.argv[1]
password = sys.argv[2]
if username == 'jason' and password == '123':
print('欢迎使用')
# 当前这个py文件逻辑代码
else:
print('用户不存在 无法执行当前文件')
六、序列化模块
1.序列化:其他数据类型转换成字符串的过程
2.反序列化:字符串转成其他数据类型
3.写入文件的数据必须是字符串,基于网络传输的数据必须是二进制
4.json模块:
所有的语言都支持json格式
支持的数据类型很少,如字符串、列表、字典、整型、元组(转成列表)布尔值
dumps和loads
import json
d = {"name":"jason"}
print(d) # {'name': 'jason'}
res = json.dumps(d) # json格式是字符串 必须是双引号 >>>: '{"name": "jason"}'
print(res,type(res)) # {"name": "jason"} <class 'str'>
res1 = json.loads(res)
print(res1,type(res1)) # {'name': 'jason'} <class 'dict'>
dump和load
import json
d = {"name":"jason"}
with open('userinfo','w',encoding='utf-8') as f:
json.dump(d,f) # dump方法接收一个文件句柄,直接将字典转换成json字符串写入文件
with open('userinfo','r',encoding='utf-8') as f:
res = json.load(f) # load方法接收一个文件句柄,直接将文件中的json字符串转换成数据结构返回
import json
d = {"name":"jason"}
with open('userinfo','w',encoding='utf-8') as f:
json_str = json.dumps(d)
json_str1 = json.dumps(d)
f.write('%s\n'%json_str)
f.write('%s\n'%json_str1)
with open('userinfo','r',encoding='utf-8') as f:
for line in f:
res = json.loads(line)
print(res,type(res))
# {'name': 'jason'} <class 'dict'>
# {'name': 'jason'} <class 'dict'>
t = (1,2,3,4)
print(json.dumps(t)) # [1, 2, 3, 4]
ensure_ascii关键字参数
import json
d1 = {'name':'猪坚强'}
print(json.dumps(d1,ensure_ascii=False)) # {"name": "猪坚强"}
5.pickel模块:
只支持python
python所有的数据类型都支持
import pickle
d = {'name':'jason'}
res = pickle.dumps(d) # 将对象直接转成二进制
print(res)
res1 = pickle.loads(res)
print(res1,type(res1)) # {'name': 'jason'} <class 'dict'>
用pickle操作文件的时候,文件的打开模式必须是b模式
七、subprocess模块
sub:子,process:进程
"""
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'))
转载于:https://www.cnblogs.com/yljbky/articles/11209790.html