collections模块
一、导入方式
from collections import xxx
二、作用
复杂的数据类型
三、方法
3.1 有名元组
from collections import namedtuple
point = namedtuple('point',['x','y'])
p = point(1,2)
print(p.x)
print(p.y)
---------------------------------------------------
1
2
3.2 默认字典
from collections import defaultdict
# dic = {'a':1}
# print(dic['b'])
dic = defaultdict(lambda :'nan') # dic = {} # 如果找不到赋了一个默认值
dic['a'] = 1
print(dic['a'])
print(dic['c']) #找不到关键字c给c赋了一个默认值nan
----------------------------------------------------------
1
nan
3.3 双端队列
# lis = [1,2,3] # 线性表
# lis.append(4) #在后面追加4
# print(lis)
from collections import deque # 链表
de = deque([1,2,3])
de.append(4) #在最后面追加4
print(de)
de.appendleft(0) #在最前面追加0
print(de) # 默认删除左边的
de.popleft()
print(de)
-------------------------------------------------------------
deque([1, 2, 3, 4])
3.4 计数器
'''比较麻烦的方法'''
s= 'programming'
# dic = {}
# for i in s:
# if i in dic:
# dic[i]+=1
# else:
# dic[i] =1
# print(dic)
-------------------------------------------------------------
{'p': 1, 'r': 2, 'o': 1, 'g': 2, 'a': 1, 'm': 2, 'i': 1, 'n': 1}
# 新方法
from collections import Counter
s= 'programming'
c = Counter() # 字典
for i in s:
c[i] +=1 #在内部自己进行了一个判断
print(c)
-----------------------------------------------------
Counter({'r': 2, 'g': 2, 'm': 2, 'p': 1, 'o': 1, 'a': 1, 'i': 1, 'n': 1})