gpt4 book ai didi

Python:将元组列表转换为嵌套字典的字典

转载 作者:太空宇宙 更新时间:2023-11-04 03:06:00 25 4
gpt4 key购买 nike

所以我手头有点问题。我有一个元组列表(由级别编号和消息组成)最终将成为 HTML 列表。我的问题是,在发生这种情况之前,我想将元组值转换为嵌套字典的字典。所以这里是示例:

# I have this list of tuples in format of (level_number, message)
tuple_list = [(1, 'line 1'), (2, 'line 2'), (3, 'line 3'), (1, 'line 4')]

# And I want to turn it into this
a_dict = {
'line 1': {
'line 2': {
'line 3': {}
}
},
'line 4': {}
}

任何帮助将不胜感激,只要它是有效的 Python 3。谢谢!

最佳答案

正如我在评论中指出的那样,如果您完全可以控制它,您应该强烈考虑更改您的传入数据结构。一个连续的元组列表绝对不适合你在这里做的事情。然而,如果你把它当作一棵树来对待,这是可能的。让我们构建一个(理智的)数据结构来解析它

class Node(object):
def __init__(self, name, level, parent=None):
self.children = []
self.name = name
self.level = level
self.parent = parent

def make_child(self, othername, otherlevel):
other = self.__class__(othername, otherlevel, self)
self.children.append(other)
return other

现在您应该能够以某种合理的方式迭代您的数据结构

def make_nodes(tuple_list):
"""Builds an ordered grouping of Nodes out of a list of tuples
of the form (level, name). Returns the last Node.
"""

curnode = Node("root", level=-float('inf'))
# base Node who should always be first.

for level, name in tuple_list:
while curnode.level >= level:
curnode = curnode.parent
# if we've done anything but gone up levels, go
# back up the tree to the first parent who can own this
curnode = curnode.make_child(name, level)
# then make the node and move the cursor to it
return curnode

一旦您的结构完成,您就可以对其进行迭代。如果您采用深度优先或广度优先,这里并不重要,所以让我们做一个 DFS 只是为了便于实现。

def parse_tree(any_node):
"""Given any node in a singly-rooted tree, returns a dictionary
of the form requested in the question
"""

def _parse_subtree(basenode):
"""Actually does the parsing, starting with the node given
as its root.
"""

if not basenode.children:
# base case, if there are no children then return an empty dict
return {}
subresult = {}
for child in basenode.children:
subresult.update({child.name: _parse_subtree(child)})
return subresult

cursor = any_node
while cursor.parent:
cursor = cursor.parent
# finds the root node
result = {}
for child in cursor.children:
result[child.name] = _parse_subtree(child)
return result

然后输入元组列表

tuple_list = [(1, 'line 1'), (2, 'line 2'), (3, 'line 3'), (1, 'line 4')]

last_node = make_nodes(tuple_list)
result = parse_tree(last_node)
# {'line 1': {'line 2': {'line 3': {}}}, 'line 4': {}}

关于Python:将元组列表转换为嵌套字典的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39457792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com