问题
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