了解Python的collections.Counter类型

了解Python的collections.Counter类型,第1张

了解Python的collections.Counter类型 python视频教程栏目介绍Python的collections.Counter类型。

collections.Counter 类型可以用来给可散列的对象计数,或者是当成多重集合来使用 —— 多重集合就是集合里的元素可以出现多次1。

collections.Counter 类型类似于其它编程语言中的 bags 或者 multisets2

(1)基本用法

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)

运行结果:

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 类型还支持集合运算。

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)

运行结果:

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})
  • 示例中的 a 与 b 都是 Counter 类型对象。这里还演示了 Counter 对象可以使用键值对的方式进行初始化 *** 作;

  • a+b 表示并集 *** 作,包含所有元素;

  • a-b 表示差集 *** 作;

  • a&b 表示交集 *** 作;

  • a|b 比较特殊,首先把所有的键囊括进来,然后比较两个对象中的对应键的最大值,作为新对象的值。比如 a 对象中有 '老虎': 3,b 对象中有 '老虎': 1,那么最后得到的对象是 '老虎': 3。

(3)正负值计数

Counter 类型中的计数器还支持负值。

c = collections.Counter(x=1, y=-1)
logging.info('+c -> %s', +c)
logging.info('-c -> %s', -c)

运行结果:

INFO - +c -> Counter({'x': 1})
INFO - -c -> Counter({'y': 1})

通过简单的 +/- 作为 Counter 类型对象的前缀,就可以实现正负计数过滤。Python 的这一设计很优雅。

相关免费学习推荐:python视频教程

以上就是了解Python的collections.Counter类型的详细内容,

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/681820.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-20
下一篇 2022-04-20

发表评论

登录后才能评论

评论列表(0条)

保存