【问题标题】:printing sum of same values from a nested list [duplicate]从嵌套列表中打印相同值的总和[重复]
【发布时间】:2019-03-08 21:30:03
【问题描述】:

我正在使用 for 循环来遍历列表,例如:

for c in classes:
    print(c.get(‘class’), c.get('plan'), c.get('type'), c.get(‘money’,{})[0].get(‘totalspent’))

我得到结果:

class1   plan1  type1 10
class2   plan2  type2 20
class3   plan3  type3 10
class2   plan2  type2 30
class3   plan3  type3 20 

我正在想办法得到类似的东西:

class1  plan1 type1 10
class2  plan2 type2 50
class3  plan3 type3 30

有没有更简单的方法来实现这一点?

【问题讨论】:

标签: python python-3.x


【解决方案1】:

我一发帖就想通了。也许将来会帮助别人:

从集合导入默认字典

output = defaultdict(int)

for c in classes:
    output[c.get('class'), c.get('plan'), c.get('type')] += c.get('money', {})[0].get('totalspent', 0)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    相关资源
    最近更新 更多