我有时间序列字典,我需要计算每个键的所有值,这是最有效的方法吗?
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}]]}
我尝试这样做(这肯定是愚蠢但有效):
total = 0
for i in DATA:
for j in DATA[i]:
for k in j[1]:
total += j[1][k]
请帮帮忙?
答案 0 :(得分:4)
将sum()
与生成器一起使用:
total = sum(sum(inner[1].values()) for outer in DATA.values() for inner in outer)
这与以下for循环的行为相同:
total = 0
for outer in DATA.values():
for inner in outer:
total += sum(inner[1].values())