【问题标题】:How to sum together all values associated with duplicates in list of lists?如何将与列表列表中的重复项关联的所有值加在一起?
【发布时间】:2018-05-08 12:16:58
【问题描述】:

我有以下列表:

x = [['A', 300], ['C', 200], ['B', 1500], ['A', 1000], ['C', 1000]]

现在我想生成一个格式相似的新列表,但是列表列表中所有重复字符串的整数相加。我想要的结果是:

x2 = [['A', 1300], ['B', 1500], ['C', 1200]]

如何做到这一点?

【问题讨论】:

  • 你尝试了什么?

标签: python duplicates nested-lists


【解决方案1】:

由于最终的结果就像一本字典,你可以用字典来制作。

import collections

x = [['A', 300], ['C', 200], ['B', 1500], ['A', 1000], ['C', 1000]]

d = collections.defaultdict(int)
for k, v in x:
    d[k] += v

x2 = d.items()
# Or list(d.items()) if you really need a list
# And list(map(list, d.items())) if you need a list of
# lists, and not a list of tuples.

【讨论】:

    猜你喜欢
    • 2012-10-23
    • 1970-01-01
    • 2011-03-04
    • 2021-11-25
    • 2023-01-09
    • 2020-02-03
    • 2021-12-27
    • 1970-01-01
    • 2020-10-29
    相关资源
    最近更新 更多