3

次のような構造でコメント ツリーをソートしようとしています。

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 レベルです

おまけ: また、元のポスターのコメントを各レベルの上部に、時間順に並べて配置したいと思います。

どんな助けでも大歓迎です!

4

1 に答える 1

0

これを並べ替えて、辞書をリストに入れ、並べ替えてから再帰できるはずです

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
于 2012-08-10T20:17:57.487 に答える