Python collections.Counter,有没有办法避免添加字符串值?

Python collections.Counter,有没有办法避免添加字符串值?,python,dictionary,collections,counter,Python,Dictionary,Collections,Counter,例如,我有两本字典 >dict_a={'total':20,'剩余]:10,'group':'group_a'} >>>dict_b={'total':30,“剩余的”:29,“group':'group_a'} 我用它来计数 >>> dict_c = Counter() >>> dict_c.update(Counter(dict_a)) >>> dict_c.update(Counter(dict_b)) >>> pr

例如,我有两本字典

>dict_a={'total':20,'剩余]:10,'group':'group_a'}
>>>dict_b={'total':30,“剩余的”:29,“group':'group_a'}
我用它来计数

>>> dict_c = Counter()
>>> dict_c.update(Counter(dict_a))
>>> dict_c.update(Counter(dict_b))
>>> print(dict_c)
{'toal': 50, 'remaining': 39, 'group': 'group_agroup_a'}
有没有办法只添加整型值?i、 e当添加时,它只添加整型值

>>> print(dict_c)
>>> {'toal': 50, 'remaining': 39, 'group': 'group_a'}
有没有办法只添加整型值

这可能不是最有效的解决方案,但您可以简单地遍历
dict_c
的键值对,检查值是否为
int
类型,以创建一个只包含整数值的新字典

从集合导入计数器
dict_a={'total':20,“剩余的”:10,“group':'group_a'}
dict_b={'total':30,“剩余的”:29,“group':'group_a'}
dict_c=计数器(dict_a)+计数器(dict_b)
dict_result={key:key的值,dict_c.items()中的值(如果是instance(value,int)}
打印(记录结果)
这将返回预期结果:

{'total':50,'剩余]:39}

您可以定义自己的函数来添加两个
计数器
对象,就像您在问题中遇到的对象一样。这是必要的,因为用于添加
计数器
对象的默认方法不能像处理输入对象那样处理对象中的非数值

from collections import Counter

def add_counters(a, b):
    """ Add numerical counts from two Counters. """
    if not isinstance(a, Counter) or not isinstance(a, Counter):
        return NotImplemented
    result = Counter()
    for elem, count in a.items():
        newcount = count + b[elem]
        try:
            if newcount > 0:
                result[elem] = newcount
        except TypeError:
            result[elem] = count  # Just copy value.

    for elem, count in b.items():
        if elem not in a and count > 0:
            result[elem] = count

    return result


dict_a = {'total': 20, 'remaining': 10, 'group': 'group_a'}
dict_b = {'total': 30, 'remaining': 29, 'group': 'group_a'}
dict_c = add_counters(Counter(dict_a), Counter(dict_b))
print(dict_c)  # -> Counter({'total': 50, 'remaining': 39, 'group': 'group_a'})

请注意,上述内容可能并不完全正确,因为第一个
计数器
参数
a
中刚刚复制到结果的任何非数字项可能会被第二个
for
循环覆盖,因此它们的最终值是第二个
计数器
中名为
b
的值。这是因为您没有准确定义在这种情况下希望发生什么。

预期的输出是什么?运行代码时,我得到了
TypeError:不支持的+操作数类型:'dict'和'dict'
我已经更新了代码@zamir我在末尾添加了预期的输出。您不能添加这样的字典,因此您现在得到的示例不正确。@martineau我使用集合中的计数器进行添加。为什么不能正确呢?你能详细说明一下吗?