python dictionary of list of list aggregate

怎甘沉沦 提交于 2021-01-29 08:05:59

问题


I have timeseries dictionary available, I need to count all the values of each keys, what's the most efficient way to do this?

DATA = {u'604': [[1361836800, {u'14885549': 52, u'91478624': 127, u'25581439': 12, u'532617990': 4}], [1361833200, {u'14885549': 38, u'91478624': 204, u'25581439': 14, u'40302362': 5, u'532617990': 2}]]}

My attempt to do this is here (which is surely idiotic but works):

total = 0
for i in DATA:
    for j in DATA[i]:
        for k in j[1]:
            total += j[1][k]

Please help?


回答1:


Using sum() with a generator:

total = sum(sum(inner[1].values()) for outer in DATA.values() for inner in outer)

This is equivalent in behavior to the following for loop:

total = 0
for outer in DATA.values():
    for inner in outer:
        total += sum(inner[1].values())


来源:https://stackoverflow.com/questions/15099683/python-dictionary-of-list-of-list-aggregate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!