Summing list of counters in python

后端 未结 2 1936
暖寄归人
暖寄归人 2021-02-11 22:12

I am looking to sum a list of counters in python. For example to sum:

counter_list = [Counter({\"a\":1, \"b\":2}), Counter({\"b\":3, \"c\":4})]

2条回答
  •  臣服心动
    2021-02-11 22:55

    The sum function has the optional start argument which defaults to 0. Quoting the linked page:

    sum(iterable[, start])

    Sums start and the items of an iterable from left to right and returns the total

    Set start to (empty) Counter object to avoid the TypeError:

    In [5]: sum(counter_list, Counter())
    Out[5]: Counter({'b': 5, 'c': 4, 'a': 1})
    

提交回复
热议问题