0

我有以下字典,我想计算键出现的次数,字典很大。

a = { (1,2):3, (1,3):5, (2,1):6 }

我想要这个结果

1: 3 times
2: 2 times
3: 1 time
4

6 回答 6

9

使用itertools.chain和一个collections.Counter

collections.Counter(itertools.chain(*a.keys()))

或者:

collections.Counter(itertools.chain.from_iterable(a.keys()))
于 2012-11-19T03:29:19.447 回答
5
>>> from collections import Counter
>>> a = { (1,2):3, (1,3):5, (2,1):6 }
>>> 
>>> Counter(j for k in a for j in k)
Counter({1: 3, 2: 2, 3: 1})
于 2012-11-19T03:30:47.450 回答
4

使用itertoolscollections.defaultdict

In [43]: a={(1,2):3,(1,3):5,(2,1):6}

In [44]: counts = collections.defaultdict(int)

In [45]: for k in itertools.chain.from_iterable(a.keys()):
   ....:     counts[k] += 1
   ....:     

In [46]: for k in counts:
    print k, ": %d times" %counts[k]
   ....:     
1 : 3 times
2 : 2 times
3 : 1 times
于 2012-11-19T03:28:47.393 回答
0

首先,这不是代码编写服务。试着先写一些,然后问一个问题。

其次,作为免费赠品,在 Python 中:

import collections
s = collections.defaultdict(int)
for j, k in a.keys():
   s[j] += 1
   s[k] += 1
for x in s.keys():
   print x + ": " + s[x] + " times"
于 2012-11-19T03:28:25.970 回答
0
from collections import Counter
items = Counter(val[2] for val in dic.values())

希望能解决。

于 2012-11-19T03:29:19.057 回答
0

使用python 3.2

from collections import Counter
from itertools import chain  

res = Counter(list(chain(*a)))
于 2012-11-19T14:24:40.487 回答