Python基于浏览模式生成树

2024-04-26 23:59:32 发布

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

我有一些用户的浏览模式,比如用“/”分隔的following。使用python生成树的最简单方法是什么。你知道吗

A/B
A/C
A/C/D
A/C/E
F/G

enter image description here


Tags: 方法用户模式following
2条回答

如果您只想通过url构建一个结构,最好从这样一个类开始

class Node(object):

    def __init__(self, name):
        self.name = name
        self.children = {}

    def insert(self, paths):
        child_name = paths.pop(0)
        if not child_name in self.children:
            self.children[child_name] = Node(child_name)
        if paths:
            self.children[child_name].insert(paths)

这就是如何使用它。你知道吗

with open('urls.txt') as urls:
    root = Node('')
    for url in urls:
        root.insert(url.split('/'))

相关问题 更多 >