from collections import defaultdict
def tree():
# A dict-based tree that automatically creates nodes when you access them.
# Note that this does not store a name for itself; it's closer to a dropdown
# menu than the little button you click to display the menu, or the contents
# of a directory rather than the directory itself.
return defaultdict(tree)
def paths_to_tree(paths):
# Make a tree representing the menu.
menu = tree()
for path in myList:
add_to = menu
# Traverse the tree to automatically create new tree nodes.
for name in path:
add_to = add_to[name]
return menu
def sort_key(item):
if isinstance(item, list):
return 1, item[0]
else:
# It's a string
return 0, item
# Recursively turn the tree into nested lists.
def tree_to_lists(menu):
lists = [[item, tree_to_lists(menu[item])] if menu[item] else item
for item in menu]
lists.sort(key=sort_key)
return lists
# Note the [0].
output = tree_to_lists(paths_to_tree(myList))[0]
myList = [['ItemB','ItemZ'],['ItemB','ItemP'],['ItemB','ItemJ','Item6'],['ItemB','ItemJ','Item5']]
from collections import defaultdict
infinitedict = lambda: defaultdict(infinitedict)
dictionary = infinitedict()
for item in myList:
d = dictionary
for i in item:
d = d[i]
类似于tobiasék的答案,但以你想要的格式,排序和所有。
(我想)好吧,它已经过测试,现在似乎可以工作了。在我们将路径列表转换成具有
defaultdict
的树,然后递归地将基于defaultdict
的树转换为基于排序列表的形式。在也许不是最优雅的方式,但这似乎很管用:
首先,我们使用} ,将列表列表转换为字典
defaultdict
的defaultdicts
,即^{现在,我们可以使用递归函数将该字典转换回树型列表:
^{pr2}$输出与您的预期输出略有不同,但这似乎对我更有意义:
或者,更接近您的预期结果(但仍然不完全相同,因为字典的中间步骤导致顺序混乱),请使用以下方法:
^{4}$输出:
相关问题 更多 >
编程相关推荐