如何连接两个计数器(自定义)

时间:2013-05-02 01:35:44

标签: python python-2.7 counter

我有两个计数器,所以我们假设为了简单:

a = "this" : 2 , "is" : 3
b = "what" : 3 , "is" : 2

现在我想连接两个这样的计数器:

concatenatedCounter = "this" : 2 , "is" : 3,2 , "what" : 3

有没有办法在Python中做到这一点?

编辑1:解决了第一个问题,下面是新问题,请帮助:)

在上面的结果中,如果我希望defaultdict包含{'this':[2,0],'是':[3,2],'what':[0,3]}),那会变化我需要做什么?

3 个答案:

答案 0 :(得分:3)

使用collections.defaultdict

In [38]: a = {"this" : 2 , "is" : 3}

In [39]: b = {"what" : 3 , "is" : 2}

In [40]: from collections import defaultdict

In [41]: collected_counter=defaultdict(list)

In [42]: for key,val in a.items():
    collected_counter[key].append(val)
   ....:     

In [43]: for key,val in b.items():
    collected_counter[key].append(val)
   ....:     

In [44]: collected_counter
Out[44]: defaultdict(<type 'list'>, {'this': [2], 'is': [3, 2], 'what': [3]})

<强>更新

>>> keys=a.viewkeys() | b.viewkeys()
>>> collected_counter=defaultdict(list)
>>> for key in keys:
    collected_counter[key].append( a.get(key,0) )
...     
>>> for key in keys:
    collected_counter[key].append( b.get(key,0) )
...     
>>> collected_counter
defaultdict(<type 'list'>, {'this': [2, 0], 'is': [3, 2], 'what': [0, 3]})

答案 1 :(得分:2)

>>> from collections import defaultdict
>>> from itertools import chain
>>> dd = defaultdict(list)
>>> a = {"this" : 2 , "is" : 3}
>>> b = {"what" : 3 , "is" : 2}
>>> for k, v in chain(a.items(), b.items()):
        dd[k].append(v)


>>> dd
defaultdict(<type 'list'>, {'this': [2], 'is': [3, 2], 'what': [3]})

答案 2 :(得分:1)

使用defaultdict

from collections import defaultdict
combinedValues = defaultdict(list)
for key in counterA.viewkeys() & counterB.viewkeys():
    combinedValues[key].extend([counterA[key], counterB[key]])