我需要从结构中提取数据并将其放入列表中,但我不知道该结构有多少层。
对于每个级别,我可以调用level.children()
,如果当前级别之下没有级别,则返回[]
,如果有,则返回返回 [object, object, ...]
,我可以在其中的每一个上再次调用 children()
。
我需要深入了解结构,直到将所有级别的数据提取到列表中。
当基于这样的结构时:
<name>John Smith</name>
<team link="http://teamwebsite.com">
<name>Team Name</name>
</team>
<games>
<location>
<venue>A stadium</venue>
</location>
</games>
列表应该是这样的:
[
[
{'name': 'name', 'attrs': {}, 'text': 'John Smith', 'parent': None},
],
[
{'name': 'team', 'attrs': {'link': 'http://teamwebsite.com'}, 'text': '', 'parent': None},
{'name': 'name', 'attrs': {}, 'text': 'Team Name', 'parent': 1}, # the reference to its parent's position in the list
],
[
{'name': 'games', 'attrs': {}, 'text': '', 'parent': None},
{'name': 'location', 'attrs': {}, 'text': '', 'parent': 1},
{'name': 'venue', 'attrs': {}, 'text': 'A stadium', 'parent': 2},
],
]
我正在尝试弄清楚我将使用什么 Python 从数据结构获取我的列表。我需要一种 self 延续的 for 循环,但我想不出一个好的解决方案。
有什么可以指引我正确的方向吗?我确信对于这类事情有一些我完全不知道但很乐意阅读的好的理论。
最佳答案
关于python - 当我不知道会有多少层时,如何遍历数据结构的所有层级以提取所有数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1663077/