Python 计算列表字典中的多个值

Python count multiple values in dictionary of list

我一直在尝试根据键计算字典中的值。但是,我无法达到预期的结果。我将在下面详细说明:

from collections import Counter
d = {'a': ['Adam','Adam','John'], 'b': ['John','John','Joel'], 'c': ['Adam','Adam','John}
# create a list of only the values you want to count,
# and pass to Counter()
c = Counter([values[1] for values in d.itervalues()])
print c

我的输出:

Counter({'Adam': 2, 'John': 1})

我希望它计算列表中的所有内容,而不仅仅是列表的第一个值。另外,我希望我的结果与密钥有关。我将在下面向您展示我想要的输出:

{'a': [{'Adam': 1, 'John': 2}, 'b':{'John': 2, 'Joel': 1}, 'c':{'Adam': 2, 'John': 1 }]}

是否有可能获得所需的输出?或者任何接近它的东西?欢迎大家提出任何建议或想法。谢谢。

尝试使用 dict comprehension

from collections import Counter
d = {'a': ['Adam','Adam','John'], 'b': ['John','John','Joel'], 'c': ['Adam','Adam','John'}
c = {i:Counter(j) for i,j in d.items()}
print c

您使用 values[1] 仅选择每个列表中的第一个元素,相反,您希望使用第一个值之后的 for 遍历每个值:

>>> from collections import Counter
>>> d = {'a': ['Adam','Adam','John'], 'b': ['John','John','Joel'], 'c': ['Adam','Adam','John']}
>>> Counter([v for values in d.itervalues() for v in values]) # iterate through each value
Counter({'John': 4, 'Adam': 4, 'Joel': 1})