转换以下内容的最佳方式是什么:
myList = [
['ItemB','ItemZ'],
['ItemB','ItemP'],
['ItemB','ItemJ','Item6'],
['ItemB','ItemJ','Item5']
]
在Python中:
newList = ['ItemB',['ItemP','ItemZ',['ItemJ',['Item5','Item6']]]]
我能够使用按Len排序的递归函数来接近但是无法找出按字母顺序按Len排序的好方法。任何帮助将不胜感激!
答案 0 :(得分:1)
也许不是最优雅的方式,但这似乎有效:
首先,我们使用defaultdict
defaultdicts
defaultdicts
,infinitedict
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]
现在,我们可以使用递归函数将该字典转换回树状列表:
def to_list(d):
lst = []
for i in d:
lst.append(i)
if d[i]:
lst.append(to_list(d[i]))
return lst
输出与预期输出略有不同,但这对我来说似乎更有意义:
>>> print to_list(dictionary)
['ItemB', ['ItemZ', 'ItemJ', ['Item6', 'Item5'], 'ItemP']]
或者,更接近您的预期结果(但仍然不完全相同,因为订单因为字典的中间步骤而被扰乱)使用此代替:
def to_list(d):
return [[i] + [to_list(d[i])] if d[i] else i for i in d]
输出:
>>> print to_list(dictionary)[0]
['ItemB', ['ItemZ', ['ItemJ', ['Item6', 'Item5']], 'ItemP']]
答案 1 :(得分:1)
类似于tobias_k的答案,但是你想要的格式,排序和所有。 (我想。)好的,它已经过测试,现在似乎正在运作。
我们将路径列表转换为defaultdict
的树,然后将基于defaultdict
的树递归转换为基于列表的排序形式。
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]