我正在尝试使用如下结构对注释树进行排序:
unsorted_dict = {
1: [id, poster, time, comment, {
2: [id, poster, time, comment, {
3: [id, poster, time, comment]
}]
}],
2: [id, poster, time, comment, {
2: [id, poster, time, comment, {
3: [id, poster, time, comment]
}]
}]
}
如果sort = newest
,我想生成一个排序列表/字典,其结构与上面相同,但每个级别按时间降序排序:
sorted_output = [
[1,'toplevel', 10:00pm, 'words...', [
[2,'secondlevel', 5:00pm, 'words...',
[3,'thirdlevel', '3:00pm', 'comment...'],
[4,'thirdlevel', '2:00am','comment']
],
[5,'secondlevel', 4:00pm, 'words...', [
[6,'thirdlevel', '3:00pm', 'comment...'],
[7,'thirdlevel', '2:00pm','comment'],
[8,'thirdlevel', '1:00pm','comment']
]
],
[9,'toplevel', 9:00pm, 'words...', [
[10,'secondlevel', 7:00pm, 'words...',
[11,'thirdlevel', '4:00pm', 'comment...'],
[12,'thirdlevel', '3:00pm','comment']
],
[13,'secondlevel', 6:00pm, 'words...', [
[14,'thirdlevel', '3:00pm', 'comment...'],
[15,'thirdlevel', '2:00pm','comment'],
[16,'thirdlevel', '1:00pm','comment']
]
]
]
对字典的每个级别进行排序并重建最终排序列表的最有效方法是什么?
注意:树的上限为3级
奖金:此外,我想将原始海报评论放在每个级别的顶部,按时间排序。
任何帮助将不胜感激!
答案 0 :(得分:0)
你应该能够将这个dict转换成一个列表,排序,然后递归
def nested_sort(hsh):
lst = list(hsh.iter_items()) # structure this however you want,e.g., build an object
# with the subhash - [1,name, etc. {}]
lst.sort()
new_lst = []
for sub_hsh in lst: # get the subhash out however you structure it above
new_lst += nested_sort(sub_hsh); # recurse