python元组转换为集合_Python:将元组列表转换为嵌套字典的字典

正如我在一篇评论中所指出的,如果你有任何控制权的话,你应该强烈考虑改变你的传入数据结构。元组的顺序列表绝对不是理想的。不过,如果你把它当作一棵树来对待,这是可能的。让我们构建一个(正常的)数据结构来解析它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

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

^{pr2}$

一旦你的结构完成,你就可以对它进行迭代。在这里,如果您选择深度优先还是广度优先,那么让我们做一个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

然后输入元组列表et voilatuple_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': {}}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值