我有一个编写工作程序的战略问题。
我有CSV文件,例如:
Column1 Column 2
------- ----------
parent1 [child1, child2, child3]
parent2 [child4, child5, child6]
child1 [child7, child8]
child5 [child10, child33]
... ...
未知这些列表中每个元素的扩展深度,我想遍历它们。
代码:
def make_parentClass(self):
for i in self.csv_rows_list:
self.parentClassList.append(parentClass(i))
# after first Parent
for i in self.parentClassList:
if i.children !=[]:
for child in i.children:
for z in self.parentClassList:
if str(child) == str(z.node_parent):
i.node_children.append(z)
self.parentClassList.remove(z)
class parentClass():
node_children = []
def __init__(self, the_list):
self.node_parent = the_list[0]
self.children = the_list[1]
如果我将找到一种迭代的方法,那么上面的代码可能是一个解决方案。让我看看您是否喜欢这个问题并且现在有意义。
输出:
我的目标是通过另一种语言构建树状视图,但首先我需要以JSON格式生成此输出。所以输出应该是这样的:
{
paren1:{'child1':{'child7':{}, 'child8':{}},
'child2': {},
'child3': {},
},
parent2: {
'child4':{},
'child5': {
'child10':{},
'child33':{}
},
'child6':{}
}
}
答案 0 :(得分:1)
我建议使用两个字典的解决方案。一种嵌套在您要转换为JSON的实际数据结构上,另一种嵌套在一个可以实际找到密钥的结构上。由于所有内容都是Python中的引用,因此您可以确保两个字典的值完全相同。仔细修改平面字典将为您构建结构。
以下代码假定您已经设法将每一行拆分为字符串parent
和列表children
,其中包含两列的值。
json_dict = {}
flat_dict = {}
for parent, children in file_iterator():
if parent in flat_dict:
value = flat_dict[parent]
else:
value = {}
flat_dict[parent] = json_dict[parent] = value
for child in children:
flat_dict[child] = value[child] = {}
运行此命令将产生json_dict
,如下所示:
{
'parent1': {
'child1': {
'child7': {},
'child8': {}
},
'child2': {},
'child3': {}
},
'parent2': {
'child4': {},
'child5': {
'child10': {},
'child33': {}
},
'child6': {}
}
}
这里是一个IDEOne link可以玩。