collections模块
#collections模块
在内置数据类型中(dict,list,set,tuple)的基础上,collections模块还提供了几个额外的数据类型Counter、deque、defaultdict、namedtuple和OrderedDict以及判断什么是可迭代对象什么是迭代器
#额外的几个数据类型
- namedtuple:生成可以使用名字来访问元素内容tuple(命名元组)
- deque:双端队列,可以快速的从另外一侧追加和推出对象
- Counter:计数器,主要用来计数
- OrderedDict:有序字典
- defaultdict:带有默认值的字典
#namedtuple
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
print(p = Point(1, 2)) >>>Point(x=1, y=2)
Circle = namedtuple('Circle', ['x', 'y', 'r'])
#####namedtuple('名称', [属性list]):
print(Circle(1,2,3)) >>>Circle(x=1, y=2, r=3)
#deque
- 队列 先进先出
from collections import deque
lst = deque([11,22,33,55])
print(lst) >>>deque([11, 22, 33, 55])
lst.append(66) ###默认从后面添加
print(lst) >>>deque([11, 22, 33, 55, 66])
lst.appendleft(44) ###从左边添加
print(lst) >>>deque([44, 11, 22, 33, 55, 66])
lst.pop() ###默认从后面开始删除
print(lst) >>>deque([44, 11, 22, 33, 55])
lst.popleft() ###从左面开始删除
print(lst) >>>deque([11, 22, 33, 55])
lst.insert(3,1111) ###按照索引插入
print(lst) >>>deque([11, 22, 33, 1111, 55])
- 栈 先进后出
lst = []
lst.append(1)
lst.append(2)
lst.append(3)
print(lst) >>>[1, 2, 3]
lst.pop()
print(lst) >>>[1, 2]
lst.pop()
print(lst) >>>[1]
lst.pop()
print(lst) >>>[]
#Counter
- 统计
lst = [11,2,2,123,1,1,123,12,12,32,12,31,23,123,21,3]
from collections import Counter
print(dict(Counter(lst)))
>>>>{11: 1, 2: 2, 123: 3, 1: 2, 12: 3, 32: 1, 31: 1, 23: 1, 21: 1, 3: 1}
#OrderedDict
- 有序字典
from collections import OrderedDict # ***
a = OrderedDict({"key1":1,"key2":2})
print(a) >>>OrderedDict([('key1', 1), ('key2', 2)])
print(a["key1"]) >>>1
#defaultdict
- 默认字典
from collections import defaultdict
dic = defaultdict(list) #生成的值为list列表
dic['key1'].append(10)
dic['key2'] = 123
print(dic)>>>defaultdict(<class 'list'>, {'key1': [10], 'key2': 123})
- 生成列表直接append
from collections import defaultdict
values = [11, 22, 33,44,55,66,77,88,99,90]
my_dict = defaultdict(list)
for value in values:
if value>66:
my_dict['k1'].append(value) ##值是列表,所以直接append
else:
my_dict['k2'].append(value)