Python新手。。。 我有一份要组织到同一个月和同一年的口述清单:
[{'date':'2008-04-23','value':'1'},
{'date':'2008-04-01','value':'8'},
{'date':'2008-04-05','value':'3'},
{'date':'2009-04-19','value':'5'},
{'date':'2009-04-21','value':'8'},
{'date':'2010-09-09','value':'3'},
{'date':'2010-09-10','value':'4'},
]
我想得到的是这样一份口述清单:
[{'date':2008-04-01,'value':'12'},
{'date':2009-04-01,'value':'13'},
{'date':2010-09-01,'value':'7'},
]
这是我的代码,它正在打印一个空列表:
from datetime import datetime
myList = [{'date':'2008-04-23','value':'1'}, {'date':'2008-04-01','value':'8'}, {'date':'2008-04-05','value':'3'}, {'date':'2009-04-19','value':'5'}, {'date':'2009-04-21','value':'8'},{'date':'2010-09-09','value':'3'},
{'date':'2010-09-10','value':'4'},
]
newList = []
newDict = {}
for cnt in range(len(myList)):
for k,v in myList[cnt].iteritems():
if k == 'date':
d = datetime.strptime(v,'%Y-%m-%d').date()
for elem in newList:
if elem['date'] != d:
newList.append({'date':d,'value':myList[cnt]['value']})
else:
newList[cnt]['value'] += myList[cnt]['value']
print newList
接受的答案是正确的,但由于排序的原因,其时间复杂度为O(n lgn)。这是一个(分期)O(n)解决方案。
这就是
Counter
的目的:如果输出必须是
dict
对象:好处:如果你想避免进口。
首先,创建一个dict
month -> list of values
。函数setdefault
对于构建这种类型的dict非常方便:其次,按月份对值求和,并将日期设置为第一天:
首先,我将对数据进行排序:
然后,我将使用
itertools.groupby
进行分组:现在,为了得到你想要的输出:
1您的数据实际上已经在这方面进行了排序,因此您可以跳过这一步。
使用itertools.groupby:
相关问题 更多 >
编程相关推荐