对两个collection.Counter()对象的内容求和 [英] Summing the contents of two collections.Counter() objects

查看:142
本文介绍了对两个collection.Counter()对象的内容求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 collections.Counter()计数器。我想以有意义的方式将其中两个结合起来。

I am working with collections.Counter() counters. I would like to combine two of them in a meaningful manner.

假设我有2个计数器,例如,

Suppose I have 2 counters, say,

Counter({'menu': 20, 'good': 15, 'happy': 10, 'bar': 5})

and

Counter({'menu': 1, 'good': 1, 'bar': 3})

我试图以:

Counter({'menu': 21, 'good': 16, 'happy': 10,'bar': 8})

我该怎么做?

推荐答案

所有您需要做的就是添加它们:

All you need to do is add them:

>>> from collections import Counter
>>> a = Counter({'menu': 20, 'good': 15, 'happy': 10, 'bar': 5})
>>> b = Counter({'menu': 1, 'good': 1, 'bar': 3})
>>> a + b
Counter({'menu': 21, 'good': 16, 'happy': 10, 'bar': 8})

来自文档


提供了几种数学运算来组合Counter对象以产生多集(计数大于零的计数器)。加减法通过将相应元素的计数相加或相减来组合计数器。

Several mathematical operations are provided for combining Counter objects to produce multisets (counters that have counts greater than zero). Addition and subtraction combine counters by adding or subtracting the counts of corresponding elements.

这篇关于对两个collection.Counter()对象的内容求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆