嵌套列表到字符串
我有一个 Test 类实例的列表。这个类有像name
和parent
这样的方法,
[Test('a', ''), Test('b', ''), Test('c', 'a'), Test('d', 'a'), Test('e', 'c')]
第一个参数是name,第二个参数是parent。 Parent arg 只是父类的arg name
。 我想将此列表转换为字符串,如下所示:
Test('a', '')
|-- Test('c', 'a')
|-- Test('e', 'c')
|-- Test('d', 'a')
Test('b', '')
我正在寻找最有效的 CPU 方法来将此列表转换为字符串。列表中的项目可以嵌套在多个(10,100,1000,..)级别,并且我不关心使用的内存。
I have a list of instances of class Test. This class have method like name
and parent
[Test('a', ''), Test('b', ''), Test('c', 'a'), Test('d', 'a'), Test('e', 'c')]
First argument is name, second parent. Parent arg is simply a arg name
of parent class.
I want convert this list to string like:
Test('a', '')
|-- Test('c', 'a')
|-- Test('e', 'c')
|-- Test('d', 'a')
Test('b', '')
I looking for the most CPU-effective way to convert this list to string. Items in list can be nested at multiples (10,100, 1000, ..) levels, and I don't care about memory used.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是按原样工作的代码。基本上将数组转换为树,然后使用递归 DFS 来打印它(如果需要,您可以使用迭代 DFS):
Here is code that works as is. Basically convert the array into a tree and then use recursive DFS to print it (you can use iterative DFS if you want):
您应该使用另一个容器,如下所示:
然后只需迭代
elements
来打印:应该打印:
您可以将缩进更改为您喜欢的任何内容(我正在使用制表符)。
You should use another container, like that:
then just iterate
elements
to print:should print:
You may change the indentation to anything you prefer (I'm using tabs).
如果您最终按照 Fiver 建议使用 DFS,则可以使用 networkx
那么这是使用 DFS 迭代它的问题
If you end up using DFS as fiver suggested you could use networkx
Then it is a mater of iterating it with DFS