Python中列表的类别树实现

2 投票
2 回答
2627 浏览
提问于 2025-04-28 13:38

我正在尝试用Python实现一个可以无限深度的分类树,里面有多个子分类。我有多个列表元素,需要从中构建这个分类树。

让我详细解释一下,这是我的列表列表。

>mylists = [
>['home', 'desktop', 'mouse', 'wireless'],
>['home', 'desktop', 'mouse', 'wired'],
>['home', 'laptop', 'mouse'],
>['home', 'laptop', '13-inch'],
>]

我希望输出的结果是:

>home
>   desktop
>        mouse
>            wireless
>            wired
>   laptop
>       mouse
>       13-inch

我明白我应该使用递归函数来遍历这些列表,做一些神奇的事情。

为了实现这个目标,我分两步来完成这个任务:

  1. 把这个嵌套列表转换成嵌套字典(这样可以保持层级关系)
  2. 把嵌套字典转换成上面所说的想要的格式。

第一步:这是我用来把嵌套列表转换成嵌套字典的代码:

>def make_rec_dict(dict):
>    d = {}
>    for path in dict:
>        current_level = d
>        for part in path:
>            if part not in current_level:
>                current_level[part] = {}
>            current_level = current_level[part]
>            #print part
>    return d
>
>make_rec_dict(mylists)
>{'home': {'laptop': {'mouse': {}, '13-inch': {}}, 'desktop': {'mouse': {'wireless': {}, 'wired': {}}}}}

第二步:为了以想要的格式显示,

spaces = { 1 : '', 2 : '>>>>', 3 : '>>>>>>>>', 4 : '>>>>>>>>>>>>', 5 : '>>>>>>>>>>>>>>>>>>>>'}
def display_recusively(dictionary, level=0):
    if type(dictionary) is dict: 
        values = []  # get all the values and parse each again
        for key, value in dictionary.iteritems():
            if value != '':
                print spaces[level], key
                values.append(value)
                level = level + 1
                return display_recusively(values, level)
            elif value == '':  # this is the last child
                print spaces[level], key

    elif type(dictionary) is list: 
        for d in dictionary:
            return display_recusively(d, level)
    else:
        print dictionary

但是这个代码的缺点是,我无法获取子元素与父元素之间的链接。我的意思是“鼠标”和“鼠标”应该是不同的,而上面的代码在循环中出现了问题。

所以请给我建议或者纠正我,帮我找到更好的方法来实现:

  • 1. 格式化的分类树,带有深度层级
  • 2. 元素应该携带父元素的信息,以便生成锚点标签(如最后一段所述)
暂无标签

2 个回答

0

这样做也能得到相同的结果-

my_lists = [['home', 'desktop', 'mouse', 'wireless'], ['home', 'desktop', 'mouse', 'wired'],
            ['home', 'laptop', 'mouse'], ['home', 'laptop', '13-inch']]

path_list = []

for lists in my_lists:

    path = ''
    for i in range(len(lists)):
        path = path + lists[i]
        if path not in path_list:
            print '  '*i + lists[i]
            path_list.append(path)
1

对于遇到同样问题的朋友们,我找到了一个解决办法 :),下面是我修改过的 display_recursively() 函数的代码:

def display_recusively(dictionary, level=0):
    if type(dictionary) is dict: 
        values = []  # get all the values and parse each again
        for key, value in dictionary.iteritems():
            parent = key
            if value != '': # recurse only when value is dict
                print spaces[level], key 
                values.append(value)
                level = level + 1
                display_recusively(values, level) 
                level = level -1 
                values = [] #sanitise the list
            elif value == '':  # this is the last child
                print spaces[level], key , "<>"

    elif type(dictionary) is list: 
        for d in dictionary:
            display_recusively(d, level)
            level = level +1
    else:
        print dictionary

撰写回答