【问题标题】:collections.Counter, is there any way to avoid adding string values?collections.Counter,有没有办法避免添加字符串值?
【发布时间】:2020-02-16 20:37:06
【问题描述】:

例如,我有两本字典。

>>> dict_a = {'total': 20, 'remaining': 10, 'group': 'group_a'}
>>> dict_b = {'total': 30, 'remaining': 29, 'group': 'group_a'}

我使用collections.Counter 进行计数。

>>> 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'}

有没有办法只添加整数类型的值?即,当添加时,它仅将整数类型值相加。

>>> print(dict_c)
>>> {'toal': 50, 'remaining': 39, 'group': 'group_a'}

【问题讨论】:

  • 预期输出是什么?
  • 运行你的代码,我得到TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
  • 我已经更新了代码。 @zamir 我在最后添加了预期的输出。
  • 你不能像那样添加字典,所以你现在得到的例子是不正确的。
  • @martineau 我正在使用集合中的计数器进行添加。为什么不能正确?能详细点吗?

标签: python dictionary collections counter


【解决方案1】:

您可以定义自己的函数来添加两个Counterobjects,就像您在问题中遇到的那样。这是必要的,因为添加 Counter 对象的默认方法无法像您输入的那样处理其中的非数字值。

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'})

请注意,上述内容可能并不完全正确,因为第一个 Counter 参数 a 中刚刚复制到结果中的任何非数字项可能会被第二个 for 循环覆盖,因此它们的最终值是第二个Counter 中的任何内容都命名为b。之所以这样,是因为您还没有准确地定义在这种情况下想要发生的事情。

【讨论】:

    【解决方案2】:

    有没有办法只添加整数类型的值?

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

    from collections import Counter
    
    dict_a = {'total': 20, 'remaining': 10, 'group': 'group_a'}
    dict_b = {'total': 30, 'remaining': 29, 'group': 'group_a'}
    dict_c = Counter(dict_a) + Counter(dict_b)
    dict_result = {key: value for key, value in dict_c.items() if isinstance(value, int)}
    print(dict_result)
    

    这会返回预期的结果:

    {'total': 50, 'remaining': 39}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-08
      • 1970-01-01
      • 2019-09-07
      • 1970-01-01
      • 2015-05-23
      • 2019-06-08
      • 2019-05-29
      • 2011-09-13
      相关资源
      最近更新 更多