我有以下字典,我想计算键出现的次数,字典很大。
a = { (1,2):3, (1,3):5, (2,1):6 }
我想要这个结果
1: 3 times
2: 2 times
3: 1 time
我有以下字典,我想计算键出现的次数,字典很大。
a = { (1,2):3, (1,3):5, (2,1):6 }
我想要这个结果
1: 3 times
2: 2 times
3: 1 time
使用itertools.chain
和一个collections.Counter
:
collections.Counter(itertools.chain(*a.keys()))
或者:
collections.Counter(itertools.chain.from_iterable(a.keys()))
>>> 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})
使用itertools
和collections.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
首先,这不是代码编写服务。试着先写一些,然后问一个问题。
其次,作为免费赠品,在 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"
from collections import Counter
items = Counter(val[2] for val in dic.values())
希望能解决。
使用python 3.2
from collections import Counter
from itertools import chain
res = Counter(list(chain(*a)))