Python标准库之collections.Counter

collections模块

Counter 统计关键字计数

初始化方式

In [3]: collections.Counter(['a','b','b','c','c','c'])
Out[3]: Counter({'c': 3, 'b': 2, 'a': 1})

In [4]: collections.Counter('abbccc')
Out[4]: Counter({'c': 3, 'b': 2, 'a': 1})

In [5]: collections.Counter({'a':1,'b':2,'c':3})
Out[5]: Counter({'c': 3, 'b': 2, 'a': 1})

In [6]: collections.Counter(a=1,b=2,c=3)
Out[6]: Counter({'c': 3, 'b': 2, 'a': 1})

更新
会累积数值

Counter.update()

访问
类似字典的访问方式

c=collections.Counter(a=1,b=2,c=3)
print c[a]

c.elements() 返回计数大于0的元素

c.most_common(3) 返回计数从高到底排序的3个计数元组列表

In [8]: c.most_common(3)
Out[8]: [('a', 4), ('b', 3), ('d', 2)]

算术操作
1 两个Counter的各个计数累计相加

c1+c2

2 第一个Counter的计数减去第二个Counter的计数,去掉不大于0的计数

c1=c2

3 & 操作,取两个Counter中最小的正数(包括0,但是会把这个元素去掉)

In [14]: c=collections.Counter(a=4,b=3,d=2,f=1)

In [15]: b=collections.Counter(a=1,b=2,c=3)

In [16]: c & b
Out[16]: Counter({'b': 2, 'a': 1})

4 | 操作,取两个Counter中各个计数的最大值

c1 | c2

待续…..

deque 双端队列

defaultdict 带默认值的字典

orderedict 有序字典

namedtuple 带属性名的元组

array 数组(仅有一种数据类型)

heapq 有序表

bisect 二分查找插入法的有序表

queue 线程安全的队列

struct 打包和解包

你可能感兴趣的:(python)