本文摘自php中文网,作者coldplay.xixi,侵删。
python视频教程栏目介绍Python的collections.Counter类型。

collections.Counter
类型可以用来给可散列的对象计数,或者是当成多重集合来使用 —— 多重集合就是集合里的元素可以出现多次1。
collections.Counter 类型类似于其它编程语言中的 bags
或者 multisets2
。
(1)基本用法
1 2 3 4 5 6 | counter = collections.Counter([ '生物' , '印记' , '考古学家' , '生物' , '枣' , '印记' ])
logging.info( 'counter -> %s' , counter)
counter.update([ '化石' , '果实' , '枣' , '生物' ])
logging.info( 'counter -> %s' , counter)
most = counter.most_common(2)
logging.info( 'most -> %s' , most)
|
运行结果:
1 2 3 | INFO - counter -> Counter({ '生物' : 2, '印记' : 2, '考古学家' : 1, '枣' : 1})
INFO - counter -> Counter({ '生物' : 3, '印记' : 2, '枣' : 2, '考古学家' : 1, '化石' : 1, '果实' : 1})
INFO - most -> [( '生物' , 3), ( '印记' , 2)]
|
示例程序中,首先使用 collections.Counter() 初始化 counter 对象,这时 counter 对象中就已经计算好当前的词语出现次数;collections.Counter()
入参为可迭代对象,比如这里的列表。接着使用 update()
方法传入新词语列表,这时 counter 对象会更新计数器,进行累加计算;最后使用 counter 对象的 most_common()
方法打印出次数排名在前 2 名的词语列表。
(2)集合运算
collections.Counter 类型还支持集合运算。
1 2 3 4 5 6 7 8 | a = collections.Counter({ '老虎' : 3, '山羊' : 1})
b = collections.Counter({ '老虎' : 1, '山羊' : 3})
logging.info( 'a -> %s' , a)
logging.info( 'b -> %s' , b)
logging.info( 'a+b -> %s' , a + b)
logging.info( 'a-b -> %s' , a - b)
logging.info( 'a&b -> %s' , a & b)
logging.info( 'a|b -> %s' , a | b)
|
运行结果:
1 2 3 4 5 6 | INFO - a -> Counter({ '老虎' : 3, '兔子' : 2, '山羊' : 1})
INFO - b -> Counter({ '山羊' : 3, '老虎' : 1})
INFO - a+b -> Counter({ '老虎' : 4, '山羊' : 4, '兔子' : 2})
INFO - a-b -> Counter({ '老虎' : 2, '兔子' : 2})
INFO - a&b -> Counter({ '老虎' : 1, '山羊' : 1})
INFO - a|b -> Counter({ '老虎' : 3, '山羊' : 3, '兔子' : 2})
|
(3)正负值计数
Counter 类型中的计数器还支持负值。
1 2 3 | c = collections.Counter(x=1, y=-1)
logging.info( '+c -> %s' , +c)
logging.info( '-c -> %s' , -c)
|
运行结果:
1 2 | INFO - +c -> Counter({ 'x' : 1})
INFO - -c -> Counter({ 'y' : 1})
|
通过简单的 +/-
作为 Counter 类型对象的前缀,就可以实现正负计数过滤。Python 的这一设计很优雅。
相关免费学习推荐:python视频教程
以上就是了解Python的collections.Counter类型的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
Python md5与sha1加密算法的详细介绍
Python怎么遍历列表进行操作
Python中__call__ 方法的使用介绍(附示例)
Python步长什么意思
Python的web服务器相关知识点
Python中如何将数字转字符串
Python while循环语句讲解与同步解析(代码示例)
Python语言支持中文吗
Python中if语句与while语句的简单介绍(附示例)
Python扫描proxy并且如何获取可用代理ip的示例分享
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » 了解Python的collections.Counter类型