汇总并合并列表及其计数

kin*_*ong 2 python list python-3.x

我有一个并排放置的数据列表.如何汇总和映射其值:

我的列表:

country = ['Australia', 'Australia', 'UAE', 'Australia', 'Israel', 'Ghana', 'Ghana']
views = [1, 2, 4, 5, 77, 5, 2]
Run Code Online (Sandbox Code Playgroud)

虽然我已经能够将它们并排映射...像这样:

"Australia: 1",
"Australia: 2",
"UAE: 4",
"Australia: 5",
"Israel: 77",
"Ghana: 5",
"Ghana: "2"
Run Code Online (Sandbox Code Playgroud)

我尝试了什么:

result = dict(zip(country, views))
{'Australia': 5, 'UAE': 4, 'Israel': 77, 'Ghana': 2}
Run Code Online (Sandbox Code Playgroud)

我想得到双方的总结和总结......像这样:

"data": {
    "countries": [
        "Australia: 8",
        "UAE: 4",
        "Israel: 77",
        "Ghana: 7"]}
Run Code Online (Sandbox Code Playgroud)

Bra*_*mon 5

您可以使用defaultdict(int)递增计数:

>>> from collections import defaultdict

>>> country = ['Australia', 'Australia', 'UAE', 'Australia', 'Israel', 'Ghana', 'Ghana']
>>> views = [1, 2, 4, 5, 77, 5, 2]

>>> summary = defaultdict(int)
>>> for c, v in zip(country, views):
...     summary[c] += v
... 
>>> summary
defaultdict(<class 'int'>, {'Australia': 8, 'UAE': 4, 'Israel': 77, 'Ghana': 7})
Run Code Online (Sandbox Code Playgroud)

使用defaultdict(int)隐式将初始计数设置为0.以下是collections 文档的解释:

将default_factory设置为int使得defaultdict对计数很有用(就像其他语言中的包或多重集).

首次遇到字母时,映射中缺少该字母,因此default_factory函数调用int()以提供默认计数零.然后,递增操作会为每个字母构建计数.

要完全达到"预期输出":

d = {}; d['data'] = {'countries': dict(summary)}
Run Code Online (Sandbox Code Playgroud)

  • 或者`collections.Counter` (2认同)