我有一个包含元组的列表:( timestamp,someOtherValue)。我想构建一个包含这样的元组的新列表:( timestamp,此时间戳的所有someOtherValue的总和)。我试图找出一些列表理解,但我被卡住了。在Python中有没有一种聪明的方法呢?
答案 0 :(得分:3)
l = [("timestamp1", 1),("timestamp1", 2),("timestamp1", 1),("timestamp2", 2)]
d = {}
for ts, val in l:
d.setdefault(ts,0)
d[ts] += val
print d.items()
[('timestamp2', 2), ('timestamp1', 4)]
或使用defaultdict:
from collections import defaultdict
l = [("timestamp1", 1),("timestamp1", 2),("timestamp1", 1),("timestamp2", 2)]
d = defaultdict(int)
for ts, val in l:
d[ts] += val
print (d.items())
[('timestamp2', 2), ('timestamp1', 4)]