python 的collections集合模块常用类

collections是Python内建的一个集合模块,提供了许多有用的集合类

# namedtuple 创建自定义的tuple
from collections import namedtuple

'''可以通过属性值来寻找,不必要使用索引值'''
point = namedtuple('point', ['x', 'y'])
p1 = point(1, 3)
print(p1.x)
print(p1.y)
p = point(101, 2)
print(p.x)
print(p.y)

# collections也可以模拟队列! deque 是指的是双端队列!
from collections import deque

q = deque(['a', 'b', 'c'])
'''左面添加数据或者右面添加数据!'''
q.append('x')
q.appendleft('y')
print(q)

# OrderedDict 顺序key字典
from collections import OrderedDict

od = OrderedDict()
od['oz'] = 2
od['oc'] = 3
od['oa'] = 1
print(od.keys())

# Counter 简单计数器 可以实现计数的功能!!
from collections import Counter

c = Counter()
for ch in 'programming':
    print(c[ch])
    #  c['a']       count of letter 'ch'
    c[ch] += 1  # 计数是0开始的,因此加一
print(c)

有的时候集合类是很方便的! 

 

posted @ 2018-05-07 11:38  十七楼的羊  阅读(138)  评论(0编辑  收藏  举报