简体   繁体   English

python中列表的类别树实现

[英]Category tree implementation of lists in python

I'm trying to implement category tree with an unlimited depth of subcategories in Python, I have multiple list elements from which I have to make this. 我正在尝试在Python中实现具有无限深度的子类别的类别树,我必须从中创建多个列表元素。

Let me explain in detail, this is my list of list. 让我详细解释一下,这是我的清单清单。

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

I want the output to be: 我希望输出为:

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

I understood that I should use a recursive function to iterate through the lists and make something magic. 我知道我应该使用递归函数来遍历列表并做出一些神奇的事情。

To achieve this, I am doing this task in 2 steps: 1. converting this nested list into nested dictionary (just to keep the hierarchy) 2. converting the nested dict into the desired formatting explained above. 为此,我分两步执行此任务:1.将嵌套列表转换为嵌套字典(只是为了保持层次结构)2.将嵌套字典转换为上述所需的格式。

Step1: Here is my code to convert nested list into nested dict: 步骤1:这是我的代码,将嵌套列表转换为嵌套字典:

>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': {}}}}}

Step2: To display in the desired format, 第2步:要以所需格式显示,

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

But the drawback of the code is, I cannot get the link of the child elements with respect to the parents. 但是代码的缺点是,我无法获得子元素相对于父元素的链接。 I mean Mouse and Mouse should be different and the drawback of the above code is its coming out of the loop.. 我的意思是Mouse和Mouse应该是不同的,并且上面代码的缺点是它循环出现了。

So please suggest me or correct me a better way to achieve: 因此,请建议我或纠正我一种更好的实现方式:

  • 1.formatted category tree with depth levels 1.格式化类别树的深度级别
  • 2.elements should carry the parents to make anchors tags (as explained in the last paragraph) 2.元素应携带父母制作锚标签(如上一段所述)

For anyone with same issue.. i figured out the way to achieve this :), here is the changed code for display_recursively(): 对于有相同问题的任何人..我想出了实现此方法的方法:),这是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

Same output can be got by doing this- 这样做可以获得相同的输出-

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM