-1

我有两个柜台,所以为了简单起见让我们假设:

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

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

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

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

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

在上面的结果中,如果我希望 defaultdict 包含 { 'this' : [2,0],'is':[3,2],'what' : [0,3]}),我需要进行哪些更改制作?

4

3 回答 3

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]})
于 2013-05-02T01:41:21.070 回答
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]})
于 2013-05-02T01:47:30.063 回答
1

使用defaultdict

from collections import defaultdict
combinedValues = defaultdict(list)
for key in counterA.viewkeys() & counterB.viewkeys():
    combinedValues[key].extend([counterA[key], counterB[key]])
于 2013-05-02T01:41:11.950 回答