gpt4 book ai didi

python - 按时间对字典内部的字典进行排序的最有效方法是什么(对于评论树)?

转载 作者:行者123 更新时间:2023-11-28 19:26:07 25 4
gpt4 key购买 nike

我正在尝试对具有如下结构的评论树进行排序:

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 层

奖励:此外,我想将原始发帖人的评论放在每个级别的顶部,按时间排序。

如有任何帮助,我们将不胜感激!

最佳答案

你应该能够将字典转换成列表,排序,然后递归

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

关于python - 按时间对字典内部的字典进行排序的最有效方法是什么(对于评论树)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11908366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com