Python Counter()计数工具

来源:互联网 发布:藏宝阁秒号软件 编辑:程序博客网 时间:2024/05/22 00:30

Table of Contents

  • 1. class collections.Counter([iterable-or-mapping])
    • 1.1. 例子
    • 1.2. 使用实例
  • 2. To Be Continued

class collections.Counter([iterable-or-mapping])

Counter 是实现的 dict 的一个子类,可以用来方便地计数。

例子

举个计数的例子,需要统计一个文件中,每个单词出现的次数。实现方法如下

# 普通青年d = {}with open('/etc/passwd') as f:    for line in f:        for word in line.strip().split(':'):            if word not in d:                d[word] = 1            else:                d[word] += 1# 文艺青年d = defaultdict(int)   with open('/etc/passwd') as f:       for line in f:           for word in line.strip().split(':'):               d[word] += 1# 棒棒的青年word_counts = Counter()with open('/etc/passwd') as f:    for line in f:word_counts.update(line.strip().split(':'))

使用实例

可以像下面例子一样来创建一个 Counter:

>>> c = Counter()                           # 创建一个新的空counter>>> c = Counter('abcasdf')                  # 一个迭代对象生成的counter>>> c = Counter({'red': 4, 'yello': 2})      # 一个映射生成的counter>>> c = Counter(cats=2, dogs=5)             # 关键字参数生成的counter# counter 生成counter, 虽然这里并没有什么用>>> from collections import Counter>>> c = Counter('abcasd')>>> cCounter({'a': 2, 'c': 1, 'b': 1, 's': 1, 'd': 1})>>> c2 = Counter(c)>>> c2Counter({'a': 2, 'c': 1, 'b': 1, 's': 1, 'd': 1})

因为 Counter 实现了字典的 __missing__ 方法, 所以当访问不存在的key的时候,返回值为0:

>>> c = Counter(['apple', 'pear'])>>> c['orange']0

counter 常用的方法:

# elements() 按照counter的计数,重复返回元素>>> c = Counter(a=4, b=2, c=0, d=-2)>>> list(c.elements())['a', 'a', 'a', 'a', 'b', 'b']# most_common(n) 按照counter的计数,按照降序,返回前n项组成的list; n忽略时返回全部>>> Counter('abracadabra').most_common(3)[('a', 5), ('r', 2), ('b', 2)]# subtract([iterable-or-mapping]) counter按照相应的元素,计数相减>>> c = Counter(a=4, b=2, c=0, d=-2)>>> d = Counter(a=1, b=2, c=3, d=4)>>> c.subtract(d)>>> cCounter({'a': 3, 'b': 0, 'c': -3, 'd': -6})# update([iterable-or-mapping]) 不同于字典的update方法,这里更新counter时,相同的key的value值相加而不是覆盖# 实例化 Counter 时, 实际也是调用这个方法# Counter 间的数学集合操作>>> c = Counter(a=3, b=1, c=5)>>> d = Counter(a=1, b=2, d=4)>>> c + d                       # counter相加, 相同的key的value相加Counter({'c': 5, 'a': 4, 'd': 4, 'b': 3})>>> c - d                       # counter相减, 相同的key的value相减,只保留正值得valueCounter({'c': 5, 'a': 2})>>> c & d                       # 交集:  取两者都有的key,value取小的那一个Counter({'a': 1, 'b': 1})>>> c | d                       # 并集:  汇聚所有的key, key相同的情况下,取大的valueCounter({'c': 5, 'd': 4, 'a': 3, 'b': 2})常见做法:sum(c.values())                 # 继承自字典的.values()方法返回values的列表,再求和c.clear()                       # 继承自字典的.clear()方法,清空counterlist(c)                         # 返回key组成的listset(c)                          # 返回key组成的setdict(c)                         # 转化成字典c.items()                       # 转化成(元素,计数值)组成的列表Counter(dict(list_of_pairs))    # 从(元素,计数值)组成的列表转化成Counterc.most_common()[:-n-1:-1]       # 最小n个计数的(元素,计数值)组成的列表c += Counter()                  # 利用counter的相加来去除负值和0的值

To Be Continued

下一篇将从源码层次剖析collection.Counter的实现, 敬请期待啦!
参见这儿: http://blog.csdn.net/imnisen1992/article/details/53135654

0 0
原创粉丝点击