说我有以下列表:
list1 = [{'position':'child','title':'dave','obj':obj,created:'2013-11-20'},
{'position':'child','title':'james','obj':obj,created:'2013-11-19'},
{'position':'child','title':'james','obj':obj,created:'2013-11-18'},
{'position':'child','title':'ian','obj':obj,created:'2013-11-17'},
{'position':'child','title':'dave','obj':obj,created:'2013-11-16'},
{'position':'child','title':'dave','obj':obj,created:'2013-11-15'},
{'position':'child','title':'dave','obj':obj,created:'2013-11-14'}]
正如您所看到的那样,它已经处于日期顺序(我希望保持这种状态)。 stackoverflow上有很多关于如何使用defaultdict
按公共条目进行分组的答案,但有没有办法按title
分组,同时保留created
顺序,如下所示:
list1 = [{'position':'parent','title':'dave root'},
{'position':'child','title':'dave','obj':obj,created:'2013-11-20'},
{'position':'parent','title':'james root'},
{'position':'child','title':'james','obj':obj,created:'2013-11-19'},
{'position':'child','title':'james','obj':obj,created:'2013-11-18'},
{'position':'parent','title':'ian root'},
{'position':'child','title':'ian','obj':obj,created:'2013-11-17'},
{'position':'parent','title':'dave root'},
{'position':'child','title':'dave','obj':obj,created:'2013-11-16'},
{'position':'child','title':'dave','obj':obj,created:'2013-11-15'},
{'position':'child','title':'dave','obj':obj,created:'2013-11-14'}]
答案 0 :(得分:3)
list1 = [{'position':'child','title':'dave','obj':'obj','created':'2013-11-20'},
{'position':'child','title':'james','obj':'obj','created':'2013-11-19'},
{'position':'child','title':'james','obj':'obj','created':'2013-11-18'},
{'position':'child','title':'ian','obj':'obj','created':'2013-11-17'},
{'position':'child','title':'dave','obj':'obj','created':'2013-11-16'},
{'position':'child','title':'dave','obj':'obj','created':'2013-11-15'},
{'position':'child','title':'dave','obj':'obj','created':'2013-11-14'}]
import itertools
import operator
list1 = [
x
for key, grp in itertools.groupby(list1, key=operator.itemgetter('title'))
for x in [{'position': 'parent', 'title': key + ' root'}]+ list(grp)
]
for x in list1:
print(x)
输出:
{'position': 'parent', 'title': 'dave root'}
{'position': 'child', 'created': '2013-11-20', 'obj': 'obj', 'title': 'dave'}
{'position': 'parent', 'title': 'james root'}
{'position': 'child', 'created': '2013-11-19', 'obj': 'obj', 'title': 'james'}
{'position': 'child', 'created': '2013-11-18', 'obj': 'obj', 'title': 'james'}
{'position': 'parent', 'title': 'ian root'}
{'position': 'child', 'created': '2013-11-17', 'obj': 'obj', 'title': 'ian'}
{'position': 'parent', 'title': 'dave root'}
{'position': 'child', 'created': '2013-11-16', 'obj': 'obj', 'title': 'dave'}
{'position': 'child', 'created': '2013-11-15', 'obj': 'obj', 'title': 'dave'}
{'position': 'child', 'created': '2013-11-14', 'obj': 'obj', 'title': 'dave'}