collections模块常用的数据类型:
(1)namedtuple(): #创建一个自定义的tuple对象,并且规定了tuple元素的个数,并可以用属性而不是索引来引用tuple的某个元素。 from collections import namedtuple
p = namedtuple('p',['x','y','z'])
p1 = p(2,3,5)
print(p1.x,p1.y,p1.z) 输出结果为:
2 3 5
(2)deque(): #使用list存储数据时,按索引访问元素很快。由于list是线性存储,数据量大的时候,插入和删除元素效率就很低。deque队列是为了高效的实现插入和删除操作的双向列表,适用于队列和栈。 from collections import deque li1 = deque([1,2,3,4,5])
li1.append('a')
li1.appendleft('m')
print(li1) li1.pop()
li1.popleft()
print(li1) 输出结果为:
deque(['m', 1, 2, 3, 4, 5, 'a'])
deque([1, 2, 3, 4, 5])
(3)defaultdict(): #使用字典的时候,如果key值不存在就会报KeyError错。如果想key不存在时,返回一个默认值,就可以用defaultdict: from collections import defaultdict dd = defaultdict(lambda :'not exist!')
dd['k1'] = ''
print(dd['k1'])
print(dd['k2']) 输出结果为:
123
not exist!
(4)有序字典 from collections import OrderedDict dd = dict([('k1',1),('k2',2),('k3',3)])
print(dd) order_dd =OrderedDict([('k1',1),('k2',2),('k3',3)])
print(order_dd) 输出结果为:
{'k3': 3, 'k2': 2, 'k1': 1}
OrderedDict([('k1', 1), ('k2', 2), ('k3', 3)])
(5)Counter(): #计数器,统计字符串里面所有元素出现次数。 from collections import Counter
s = "A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. " c = Counter(s)
print(c.most_common(5)) #统计出现次数最多的5个元素 输出结果为:
[(' ', 30), ('e', 18), ('s', 15), ('a', 13), ('t', 13)]