Python列表结构修改

2024-09-28 22:00:29 发布

您现在位置:Python中文网/ 问答频道 /正文

转换以下内容的最佳方法是什么:

myList = [
          ['ItemB','ItemZ'],
          ['ItemB','ItemP'],
          ['ItemB','ItemJ','Item6'],
          ['ItemB','ItemJ','Item5']
         ]

在Python中:

^{pr2}$

我可以使用一个按Len排序的递归函数,但无法找到一个按Len然后按字母顺序排序的好方法。任何帮助将不胜感激!在


Tags: 方法len排序顺序字母mylistpr2itemb
2条回答

类似于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]

也许不是最优雅的方式,但这似乎很管用:

首先,我们使用defaultdictdefaultdicts,即^{},将列表列表转换为字典

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]

现在,我们可以使用递归函数将该字典转换回树型列表:

^{pr2}$

输出与您的预期输出略有不同,但这似乎对我更有意义:

>>> print to_list(dictionary)
['ItemB', ['ItemZ', 'ItemJ', ['Item6', 'Item5'], 'ItemP']]

或者,更接近您的预期结果(但仍然不完全相同,因为字典的中间步骤导致顺序混乱),请使用以下方法:

^{4}$

输出:

>>> print to_list(dictionary)[0]
['ItemB', ['ItemZ', ['ItemJ', ['Item6', 'Item5']], 'ItemP']]

相关问题 更多 >