开发者

Python: traverse tree adding html list (ul)

开发者 https://www.devze.com 2023-01-11 15:45 出处:网络
I have this python code that will traverse a tree structure. I am trying to add ul and li tags to the function but I am not very succesful. I though I was able to keep the code clean without to many c

I have this python code that will traverse a tree structure. I am trying to add ul and li tags to the function but I am not very succesful. I though I was able to keep the code clean without to many conditionals but now I ain't so sure anymore.

def findNodes(nodes):

    def traverse(n开发者_如何学Pythons):
        for child in ns:
            traverse.level += 1
            traverse(child.Children)
            traverse.level -= 1

    traverse.level = 1
    traverse(nodes)

This is the base function I have for traversing my tree structure. The end result should be nested ul and li tags. If need I can post my own not working examples but they might be a little confusing.

Update: Example with parameter

def findNodes(nodes):

    def traverse(ns, level):
        for child in ns:
            level += 1
            traverse(child.Children, level)
            level -= 1

    traverse(nodes, 1)


I removed the unused level parameter. Adding in any sort of text is left as an exercise to the reader.

def findNodes(nodes):
    def traverse(ns):
        if not ns:
            return ''

        ret = ['<ul>']
        for child in ns:
            ret.extend(['<li>', traverse(child.Children), '</li>'])
        ret.append('</ul>')
        return ''.join(ret)

    return traverse(nodes)
0

精彩评论

暂无评论...
验证码 换一张
取 消