我有一些像这样的列表
[ ['2000-01-01', 1.0], ['2000-02-01', 2.0] ]
[ ['2000-01-01', 2.0], ['2000-02-01', 1.0], ['2000-03-01', 3.0] ]
[ ['2000-01-01', 3.1], ['2000-02-01', 2.0], ['2000-03-01', 1.4] ]
如何合并datatime并将值汇总得到像这样的列表
[ ['2000-01-01', 6.1], ['2000-02-01', 5.0], ['2000-03-01', 4.4] ]
列表中元素的类型是[datetime,double]
答案 0 :(得分:1)
在此处使用collections.defaultdict()
。请参阅代码段。
>>> a = [ ['2000-01-01', 1.0], ['2000-02-01', 2.0] ]
>>> b = [ ['2000-01-01', 2.0], ['2000-02-01', 1.0], ['2000-03-01', 3.0] ]
>>> c = [ ['2000-01-01', 3.0], ['2000-02-01', 2.0], ['2000-03-01', 1.0] ]
>>> from collections import defaultdict
>>> m = defaultdict(int)
>>> d = a + b + c
>>> d
[['2000-01-01', 1.0], ['2000-02-01', 2.0], ['2000-01-01', 2.0], ['2000-02-01', 1.0], ['2000-03-01', 3.0], ['2000-01-01', 3.0], ['2000-02-01', 2.0], ['2000-03-01', 1.0]]
>>> for date, count in d:
m[date] += count
>>> m.items()
[('2000-02-01', 5.0), ('2000-03-01', 4.0), ('2000-01-01', 6.0)]
答案 1 :(得分:0)
对于所有类似Excel的编程,我建议使用Pandas,因为它是为此而制作的。 但是如果你想继续使用标准的lib,那么Counter就足够了。
答案 2 :(得分:0)
from collections import Counter
result = Counter()
result += Counter(dict([ ['2000-01-01', 1], ['2000-02-01', 2] ]))
result += Counter(dict([ ['2000-01-01', 2], ['2000-02-01', 1], ['2000-03-01', 3] ]))
result += Counter(dict([ ['2000-01-01', 3], ['2000-02-01', 2], ['2000-03-01', 1] ]))
result.most_common() # => [('2000-01-01', 6), ('2000-02-01', 5), ('2000-03-01', 4)]
答案 3 :(得分:0)
使用Counter
#inputList is List containg
from collections import Counter
from operator import itemgetter
def mergeAndGetSum(inputList):
cnt = Counter()
#get counts for each date
for list1 in inputList:
for list2 in list1:
cnt[list2[0]] += list2[1]
ret = []
#creaet the output list
for key in cnt:
ret.append([key,cnt[key]])
#sort output list based on dates
ret.sort(key=itemgetter(0))
return ret
if __name__ == "__main__":
listOfLists = [
[ ['2000-01-01', 1], ['2000-02-01', 2] ],
[ ['2000-01-01', 2], ['2000-02-01', 1], ['2000-03-01', 3] ],
[ ['2000-01-01', 3], ['2000-02-01', 2], ['2000-03-01', 1] ]
]
ret = mergeAndGetSum(listOfLists)
print ret