1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > python中collections中的counter类_了解Python的collections.Counter类型

python中collections中的counter类_了解Python的collections.Counter类型

时间:2019-03-07 23:05:53

相关推荐

python中collections中的counter类_了解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视频教程

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。