Summing list of counters in python

后端 未结 2 1941
暖寄归人
暖寄归人 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 23:02

    This version was faster in my experience. This is upper bound by O(log(n)).

    def sum_counters(counter_list):
    
        '''
        Recursive counter with a O(log(n)) Complexity
        '''
    
        if len(counter_list) > 10:
    
            counter_0 = sum_counters(counter_list[:int(len(counter_list)/2)])
            counter_1 = sum_counters(counter_list[int(len(counter_list)/2):])
    
            return sum([counter_0, counter_1], Counter())
    
        else:
    
            return sum(counter_list, Counter())
    
    global_counter = sum_counters(counter_list)
    

提交回复
热议问题