2
我有一個文件系統的字典表示,看起來像這樣。Python:網絡文件列表的字典
{
"en": {
'file_name_1': [{meta representation of file_name_1}] or False,
{'folder_name': {
'index': [{meta repr. of the index}] or False
'sub_file_1': [{meta repr. of file_name_1}] or False,
}
}
}
"fr": {
<...>
}
'tree_root': path to the tree's parent node
}
給出這棵樹(文件或文件夾)中的一個葉子的路徑,我想表示通向該葉子的樹作爲HTML嵌套列表。
我不相信我的樹會變得很深,但爲了快速起見,我正考慮在葉子的路徑上只運行一次。
這是我現在有:(。self.tree
是我的字典裏,leaf_path
我,嗯葉路我想和清理我的簡單代碼)
rel_URI = [key for key in leaf_path.split(os.sep)]
stack = []
html = u'<ul>'
for key in rel_URI:
stack.append(key)
obj = reduce(dict.get, stack, self.tree)
if isinstance(obj, dict): # a subdir
html += u'<ul>'
for _dir in obj.iterkeys() if isinstance(_dir, dict):
if _dir == rel_URI[len(stack)]: # in the leaf_path
html += u'<li class="folder">%s</li>' % self.getTitle(obj, _dir)
else: # not in the leaf_path
html += u'<li class="folder, far">%s</li>'% self.getTitle(obj,_dir)
for _file in obj.iterkeys() if isinstance(_file, list):
html += u'<li class="file, far">%s</li>'% obj[0]['title']
html += u'</ul>'
else: # the leaf file
item = u'<li class="file">%s</li>' % obj[0]['title']
html += '</ul>'
我有麻煩搞清楚如何巢下一個子樹進入迭代:它是我完全斷開了這一步的下一步,因此我最終得到了一個混亂的嵌套文件列表。我的麻煩
- 部分原因是類型的字典是沒有順序的
你會如何着手建立名單?
「我的一部分麻煩是,字符串沒有排序」 - 爲什麼不使用[OrderdDicts](http://docs.python.org/2/library/collections.html#collections.OrderedDict)? – Bach
嗯,是的,你當然是對的。 我不知道這個選項。 RTPM,我應該有。 閱讀Python手冊 – Benoit