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的官方文档

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值