collections模块
from collections import 功能
1.from collections import namedtuple(命名元祖)
格式:
from collections import namedtuple
t = namedtuple('元祖名',[可迭代对象])
例1.1:
from collections import namedtuple t = namedtuple('one_tuple',['a','b','c']) print(t(1,2,3))
结果:
one_tuple(a=1,b=2,c=3)
t1 = t(1,2,3)
print(t1.a) ---> 1 {t1.b-->2;t1.c--->3}
例1.2:(结构化时间)
from collections import namedtuple t = namedtuple('time_tuple',['年','月','日','时','分','秒']) t1 = t(19,1,1,1,1,1) 结果: time_tuple(年=19,月=1,日=1,时=1,分=1,秒=1)
print(t1.年)-->19
2.from collections import Counter(计数器)
例2.1
from collections import Counter s = 'abcmkkdmbdcadkmd' c = Counter(s) print(c) 结果: (默认按每个字母出现次数来降序排列) Counter({'d':4,'m':3,'k':3,'a':2,'b':2,'c':2})
例2.2
dic = {} s = 'abcmkkdmbdcadkmd' for i in s: dic[i] = dic.get(i,0)+1 print(dic)
3.from collections import defaultdict(默认字典)
例3.1
from collections import defaultdict dic = {}
dic = defaultdict(set) print(dic['key']) --> set(),空集合
例3.2
有如下值集合 [11,22,33,44,55,66,77,88,99,90],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。
常规做法: lst = [11,22,33,44,55,66,77,88,99,90] dic = {} for i in lst:
if i > 66:
dic.setdefault('k1',[]).append(i)
else:
dic.setdefault('k2',[]).append(i)
print(dic)
使用defaultdict
from collections import defaultdict
lst = [11,22,33,44,55,66,77,88,99,90]
dic = defaultdict(lst)
for i in lst:
if i > 66:
dic['k1'].append(i)
else:
dic['k2'].append(i)
print(dic)
4.from collections import deque(双向队列)
d = deque() d.append('小一') append在末尾追加 d.append('小二') d.append('小三') d.append('小四') print(d)
结果为:deque(['小一','小二','小三','小四'])
d = deque() d.append('小一') d.appendleft('小二') d.appendleft('小三') d.append('小四')
结果为:deque(['小三','小二','小一','小四'])
序列化
shelve使用场景:没有强调使用固定的序列化,就可以使用shelve
shelve是基于pickle实现的
import shelve
f = shelve.open('ss') 创建了一个字典 f['name'] = 'alex' 字典的增加,字典的键必须是字符串,值没有要求 f['age'] = 999
print(f) 一个内存地址 print(f['name']) 字典的查看 print(f.get('name'))
f.pop('age') 删除
只能通过for来看:
for i in f: print(i) for i in f.keys(): print(i) 拿到的都是字典的键 for k,v in f.items(): print(k,v)
避坑操作
如果出现报错,有一个是回写错误,还有一个就是flag = r
import shelve f = shelve.open('ss') f['name'] = '小一' f.close() f1 = shelve.open('ss',writeback = True) f1['name'] = '小二' f1.close() f = shelve.open('ss') print(f['name']) 如果出现了回写不成功,在open中添加(writeback = True)
(只读)
import shelve f = shelve.open('ss') f['name'] = '小一' f.close() f1 = shelve.open('ss',flag = 'r') f1['name'] = '小二' f1.close() f = shelve.open('ss') print(f['name'])
shutil模块
高级文件模块,有压缩功能
import shutil shutil.copyfile(r'拷贝的文件路径',r'路径\新文件名')
第一个参数是原文件,第二个参数是要拷贝的位置