You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对Python的Counter列表中的元素进行求和?

如何对Counter列表中的元素求和?

嗨,这个问题其实很容易解决,Python的collections.Counter本身就支持加法操作,这里有两种实用的方法来完成列表中所有Counter元素的求和:

  • 使用sum()函数(简洁写法)
    Counter实现了加法协议,所以可以直接用sum()函数来累加列表里的所有Counter。需要注意的是必须指定初始值为Counter(),否则默认初始值是0,会引发类型错误(整数和Counter无法相加)。示例代码如下:

    from collections import Counter
    
    # 你的Counter列表
    counter_list = [
        Counter({'A': 2, 'B': 2, 'C': 1}),
        Counter({'A': 3, 'B': 3, 'C': 2}),
        Counter({'A': 4, 'B': 4, 'C': 4}),
        # ... 剩余的Counter元素
    ]
    
    total_counter = sum(counter_list, Counter())
    print(total_counter)
    
  • 循环累加(直观写法)
    如果你更喜欢更直观的逻辑,可以通过循环逐个累加每个Counter到一个空的总Counter中,利用Counter的+=操作符自动合并相同键的数值:

    from collections import Counter
    
    counter_list = [
        Counter({'A': 2, 'B': 2, 'C': 1}),
        Counter({'A': 3, 'B': 3, 'C': 2}),
        # ... 剩余的Counter元素
    ]
    
    total_counter = Counter()
    for cnt in counter_list:
        total_counter += cnt
    
    print(total_counter)
    

两种方法最终都会得到一个包含所有键的总Counter,每个键的数值是列表中所有Counter对应键数值的总和。

内容的提问来源于stack exchange,提问作者user8650813

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:16:06