【问题标题】:Getting totals from list of lists and apply it to a dictionary [duplicate]从列表列表中获取总数并将其应用于字典 [重复]
【发布时间】:2016-03-21 22:16:22
【问题描述】:

我有一个这样的列表:

[['blah', 5], ['blah', 6], ['blah',7], ['foo', 5], ['foo', 7]]

我想要做的是创建一个字典列表,其中列表的第一个索引是关键字,第二个是运行总数。

最终结果需要如下所示:

[{'name': 'blah', 'total': 18}, {'name': 'foo', 'total': 12}]

【问题讨论】:

  • 您是否尝试过编写此代码?你能展示你的尝试并解释什么不适合你吗?

标签: python


【解决方案1】:

我会在这里使用计数器:

from collections import Counter

res = Counter()
for k, v in data:
    res.update({k: v})

print(res)

输出:

Counter({'blah': 18, 'foo': 12})

但如果你真的想要你要求的输出:

final = [{'name': k, 'total': v} for k, v in res.items()]
print(final)

输出:

[{'total': 18, 'name': 'blah'}, {'total': 12, 'name': 'foo'}]

【讨论】:

  • 非常感谢!老实说,我从来没有想过使用集合,这对我来说很愚蠢。你的回答正是我所需要的。
【解决方案2】:

您可以使用reduce 遍历所有元素并将它们汇总:

from functools import reduce

lists = [['blah',5],['blah',6],['blah',7],['foo',5],['foo',7]]

def count(total, item):
  key, val = item[0], item[1]
  if key not in total:
    total[key] = 0 
  total[key] += val 
  return total

totals = reduce(count, lists, {}) 
print(totals)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-13
    • 2019-05-25
    • 2019-09-25
    • 2020-04-18
    • 2021-02-11
    • 1970-01-01
    • 2023-01-24
    • 2020-11-25
    相关资源
    最近更新 更多