python counter转换为列表_python collections.Counter笔记

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,counter转换为列表)