python counter_Python Counter()计数工具

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')

>>> c

Counter({'a': 2, 'c': 1, 'b': 1, 's': 1, 'd': 1})

>>> c2 = Counter(c)

>>> c2

Counter({'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)

>>> c

Counter({'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相减,只保留正值得value

Counter({'c': 5, 'a': 2})

>>> c & d # 交集: 取两者都有的key,value取小的那一个

Counter({'a': 1, 'b': 1})

>>> c | d # 并集: 汇聚所有的key, key相同的情况下,取大的value

Counter({'c': 5, 'd': 4, 'a': 3, 'b': 2})

常见做法:

sum(c.values()) # 继承自字典的.values()方法返回values的列表,再求和

c.clear() # 继承自字典的.clear()方法,清空counter

list(c) # 返回key组成的list

set(c) # 返回key组成的set

dict(c) # 转化成字典

c.items() # 转化成(元素,计数值)组成的列表

Counter(dict(list_of_pairs)) # 从(元素,计数值)组成的列表转化成Counter

c.most_common()[:-n-1:-1] # 最小n个计数的(元素,计数值)组成的列表

c += Counter() # 利用counter的相加来去除负值和0的值

Next

下一篇将从源码层次剖析collection.Counter的实现, 敬请期待啦!

参见这儿: http://www.cnblogs.com/nisen/p/6055980.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值