【发布时间】:2012-11-06 23:41:00
【问题描述】:
我有以下字典,我想计算键出现的次数,字典很大。
a = { (1,2):3, (1,3):5, (2,1):6 }
我想要这个结果
1: 3 times
2: 2 times
3: 1 time
【问题讨论】:
-
键只能出现一次。你在数别的东西
标签: python list dictionary key tuples
我有以下字典,我想计算键出现的次数,字典很大。
a = { (1,2):3, (1,3):5, (2,1):6 }
我想要这个结果
1: 3 times
2: 2 times
3: 1 time
【问题讨论】:
标签: python list dictionary key tuples
首先,这不是代码编写服务。试着先写一些,然后问一个问题。
其次,作为免费赠品,在 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"
【讨论】:
使用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
【讨论】:
from collections import Counter
items = Counter(val[2] for val in dic.values())
希望对它进行排序。
【讨论】:
使用itertools.chain 和collections.Counter:
collections.Counter(itertools.chain(*a.keys()))
或者:
collections.Counter(itertools.chain.from_iterable(a.keys()))
【讨论】:
collections.Counter
collections.Counter打败我的方法!真希望我能想到这一点。此外,itertools.chain.from_iterable 将不再需要使用 *
itertools.chain.from_iterable() 绝对优于生成器表达式。
>>> 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})
【讨论】:
js、ks 和as 的顺序 :) 尽管如此,非常好的解决方案。
使用python 3.2
from collections import Counter
from itertools import chain
res = Counter(list(chain(*a)))
【讨论】:
list。 Counter 很乐意使用任何可迭代对象。