collections 模块

collections模块

python内置数据类型: str, int, tuple, dict
collections模块提供额外的数据类型:
1. namedtuple() : 可用用名字来访问元素内容的tuple 子类
2. deque: 双端队列,可以加快的从另一侧追加和推出对象
3. counter: 计数器
4. orderedDict: 有序字典
5. defaultdict: 有默认值的字典

namedtuple

import collections
# 给元组和元组中的每个元素起名字(元组是有序的,可以通过索引来取值)
from collections import namedtuple
persons = [('clerk',18),('octivia',20),('mephy',19)]
PERSON = namedtuple('person',['name','age'])  # 给元组起名字,并给每个元素起名字
for person in persons:
    person = PERSON._make(person)  # 结果产生一个对象
    print(person,type(person))
# 结果 person(name='clerk', age=18) 。。。

deque

double-ended queue 双端队列
# 优点: 实现从队列头部快速增加和取出对象 .popleft()   .appendleft() ----时间复杂度 o(1)
#        相当于 list 的 insert(0,v)  l.pop(0) ---- 时间复杂度 o(n)

d = deque([1,2,3,4])
print(d)
d.rotate(1)  # 把最后一个数字放在最前面deque([4, 1, 2, 3])
print(d)
d.rotate(2)  # 把最后两个数字放在前面deque([2, 3, 4, 1])
print(d)

# rotate 实现无线循环
import sys
import time
from collections import deque
fancy_loading = deque('>-----------')
while True:
  print('
%s'%''.join(fancy_loading),fancy_loading.rotate(1),sys.stdout.flush(),time.sleep(0.08))

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 key
 '''
c = Counter(s)
# 出现频率最高的五个字符
letters = c.most_common(5)
print(letters)
# 结果[(' ', 24), ('e', 14), ('s', 10), ('o', 9), ('t', 9)]

ordereddict

from collections import OrderedDict
# 有序字典
items = (('a',1),('b',2),('c',3))
regular_dic = dict(items)
ordered_dic = OrderedDict(items)  #循环打印出来的key 是有序的

defaultdict

# 给dict 设置默认值,当key 不存在时返回默认值
# 默认值是调用函数产生的
from collections import defaultdict

def task():
    return 2
d = defaultdict(task)
d['k'] = 'aaa'
print(d['k'])   # 当key存在时,返回对应value
print(d['k2'])  # 当key 不存在时,调用task函数

ChainMap

# 合并字典,但不是真的合并,是在内部储存一个key到每一个字典的映射
a = {'a': 1, 'b': 2}
b = {'x': 3, 'y': 5}
a.update(b)
print(a)   # 合并两个字典,但是会改变a

# 不改变两个字典,得到一个新的合并后的字典
from collections import ChainMap

c = {'z':5,'y':6}
e = ChainMap(a,b,c)
print(e['y'])  # 有相同值,取第一个
# 新添加的值会放在第一个字典个中
# 有相同的值,取第一个,删第一个
原文地址:https://www.cnblogs.com/Afrafre/p/11128984.html