我有defaultdict
,然后转换为字典。现在我正在寻找一种方法来计算按值分组的项目。我的意思是:
dict = {1: [103], 2: [9], 3: [3, 4], 4: [103, 106], 10: [3, 4], 11: [1, 9], 28: [1]}
for key in dict.items():
print key
(1, [103])
(2, [9])
(3, [3, 4])
(4, [103, 106])
(10, [3, 4])
(11, [1, 9])
(28, [1])
item : total
{4 : 2, 106 : 1} ...
我该怎么做?
答案 0 :(得分:7)
您可以使用collections.Counter
来计算值列表中每个元素的出现次数,例如
>>> from collections import Counter
>>> Counter(value for values in d.itervalues() for value in values)
Counter({1: 2, 3: 2, 4: 2, 103: 2, 9: 2, 106: 1})
Counter
只是字典的子类。所以,你可以像任何其他字典一样使用它
可以使用itertools.chain.from_iterable
完成值的展平,就像这样
>>> from collections import Counter
>>> from itertools import chain
>>> Counter(chain.from_iterable(d.itervalues()))
Counter({1: 2, 3: 2, 4: 2, 103: 2, 9: 2, 106: 1})
答案 1 :(得分:0)
这是另一种方法,除了基础知识之外什么都不用。
d = {1: [103], 2: [9], 3: [3, 4], 4: [103, 106], 10: [3, 4], 11: [1, 9], 28: [1]}
answer = {} # store the counts here
for key in d:
for value in d[key]:
if value in answer:
# if the key is already in the answer
answer[value] += 1
else:
# if the key has never been counted before
# then add it to the answer and set its value to 1
answer.update({value:1})
for key in answer:
print key, answer[key]
打印:
1 2
3 2
4 2
103 2
9 2
106 1
答案 2 :(得分:0)
m_dict = dict
n = {}
for k, v in m_dict.iteritems():
for j in v:
n[j] = (n[j] + 1 if n.get(j) != None else 1)
print n
结果:
{1: 2, 3: 2, 4: 2, 9: 2, 103: 2, 106: 1}
或者:
m_dict = dict
n = sum([v for k,v in m_dict.iteritems()], [])
c = {j : n.count(j) for j in n}
print c
结果:
{1: 2, 3: 2, 4: 2, 9: 2, 103: 2, 106: 1}