码迷,mamicode.com
首页 > 编程语言 > 详细

python collections.Counter笔记

时间:2015-12-23 21:19:31      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:

Counter是dict的子类,所以它其实也是字典。只不过它的键对应的值都是计数,值可以是任意整数。下面是四种创建Counter实例的例子:

>>> c = Counter()                           # a new, empty counter
>>> c = Counter(‘gallahad‘)                 # a new counter from an iterable
>>> c = Counter({‘red‘: 4, ‘blue‘: 2})      # a new counter from a mapping
>>> c = Counter(cats=4, dogs=8)             # a new counter from keyword args

以第二种为例,看下效果

c = Counter(‘gallahad‘)   
print(c)

输出就是一个字典

Counter({‘a‘: 3, ‘l‘: 2, ‘g‘: 1, ‘d‘: 1, ‘h‘: 1})

Counter能自动对字符串,列表等可迭代的对象里面的元素计数并转换成字典,非常好用

下面是一些Counter对象的常用函数

sum(c.values())                 # total of all counts
c.clear()                       # reset all counts
list(c)                         # list unique elements
set(c)                          # convert to a set
dict(c)                         # convert to a regular dictionary
c.items()                       # convert to a list of (elem, cnt) pairs
Counter(dict(list_of_pairs))    # convert from a list of (elem, cnt) pairs
c.most_common()[:-n-1:-1]       # n least common elements
+c                              # remove zero and negative counts

并且Counter对象还可以做加法,如下

>>> c = Counter(a=3, b=1)
>>> d = Counter(a=1, b=2)
>>> c + d                       # add two counters together:  c[x] + d[x]
Counter({‘a‘: 4, ‘b‘: 3})
>>> c - d                       # subtract (keeping only positive counts)
Counter({‘a‘: 2})
>>> c & d                       # intersection:  min(c[x], d[x])
Counter({‘a‘: 1, ‘b‘: 1})
>>> c | d                       # union:  max(c[x], d[x])
Counter({‘a‘: 3, ‘b‘: 2})

 

注:例子全部来自python3.5的官方文档

 

  

 

python collections.Counter笔记

标签:

原文地址:http://www.cnblogs.com/duyang/p/5071050.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!