collections模块
复杂的数据类型
有名元祖
p=(1,2)
from collections import namedtuple
point=namedtuple('point',['x','y'])
p=point(1,2)
print(p.x)
print(p.y)
1
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'])
1
nan
双端队列
from collections import deque
de=deque([1,2,3])
de.append(4)
print(de)
de.appendleft(0)
print(de)
de.popleft()
de.popleft()
print(de)
deque([1, 2, 3, 4])
deque([0, 1, 2, 3, 4])
deque([2, 3, 4])
计数器
from collections import Counter
s= 'programming'
# dic = {}
# for i in s:
# if i in dic:
# dic[i]+=1
# else:
# dic[i] =1
# print(dic)
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})