【问题标题】:Python count multiple values in dictionary of listPython在列表字典中计算多个值
【发布时间】:2016-10-15 10:53:55
【问题描述】:

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

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 }]}

是否有可能获得所需的输出?或者有什么接近的?我欢迎您提出任何建议或想法。谢谢。

【问题讨论】:

  • 这个问题已经被问了很多次了。
  • 嗨,Marcus,我已经尝试在网上搜索几个小时的解决方案。不幸的是,我找不到它。可以给我链接吗?谢谢。

标签: python list dictionary counter


【解决方案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

【讨论】:

  • 您好,您能详细说明一下吗?对不起。我对 python 还是很陌生。谢谢!
  • 这是您想要的解决方案吗?查看python dict comprehensiondocs.python.org/2/library/collections.html#collections.Counter。很简单
  • 对不起。我可以根据您提供的链接找到与字典理解相关的信息。你给我一个错误的链接吗?
  • 链接是关于Counter。关于dict comprehensionpython.org/dev/peps/pep-0274
  • 我已经阅读过它。这就是我要的。但我不知道我该怎么做呢?对不起。你有什么想法吗?谢谢。
【解决方案2】:

您只使用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})

【讨论】:

  • 您好,您的解决方案很棒。但是,外部是否有可能产生链接到字典的结果?例如{'a': [{'Adam': 1, 'John': 2} 谢谢!
猜你喜欢
  • 2021-12-04
  • 1970-01-01
  • 1970-01-01
  • 2020-08-14
  • 2022-06-27
  • 1970-01-01
  • 1970-01-01
  • 2020-07-19
  • 2020-11-24
相关资源
最近更新 更多