Python - 将列表列表转换为树状字典
给定一个嵌套列表,我们希望将其转换为一个字典,其元素可以被视为树形数据结构的一部分。在本文中,我们将看到将嵌套列表转换为添加字典的两种方法,其元素表示树状数据结构。
使用切片
我们通过切片反转列表中的项目,然后检查该项目是否在列表中存在。如果不存在,则忽略它,否则将其添加到树中。
示例
def CreateTree(lst):
new_tree = {}
for list_item in lst:
currTree = new_tree
for key in list_item[::-1]:
if key not in currTree:
currTree[key] = {}
currTree = currTree[key]
return new_tree
# Given list
listA = [['X'], ['Y', 'X'], ['Z', 'X'], ['P', 'Z', 'X']]
print(CreateTree(listA))运行以上代码将得到以下结果:
输出
{'X': {'Y': {}, 'Z': {'P': {}}}}使用 reduce 和 getitem
我们使用 functools 和 operator 模块来获取函数 reduce 和 getitem。使用这些函数,我们定义两个函数来从列表中获取项目并将项目设置到树结构中。这里我们也使用切片方法反转列表的元素,然后应用两个创建的函数来创建元素为树结构的字典。
示例
from functools import reduce
from operator import getitem
def getTree(tree, mappings):
return reduce(getitem, mappings, tree)
def setTree(tree, mappings):
getTree(tree, mappings[:-1])[mappings[-1]] = dict()
# Given list
lst = [['X'], ['Y', 'X'], ['Z', 'X'], ['P', 'Z', 'X']]
tree = {}
for i in lst:
setTree(tree, i[::-1])
print(tree)运行以上代码将得到以下结果:
输出
{'X': {'Y': {}, 'Z': {'P': {}}}}
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP