问题在于,我始终无法按以下所述将此csv文件放入Node类,是否有最佳实践来避免多个循环且超出索引范围?
╔════════╦═══════╦════════╦════════╦════════╗
║ root1 ║ root2 ║ root3 ║ root4 ║ root5 ║
╠════════╬═══════╬════════╬════════╬════════╣
║ cmd-28 ║ D-145 ║ D-113 ║ A-180 ║ 28Z01 ║
║ ║ ║ ║ A-181 ║ 28Z02 ║
║ ║ ║ ║ A-234 ║ 28Z03 ║
║ ║ ║ ║ D-030 ║ 28Z04 ║
║ ║ ║ ║ other ║ 90Z02Z ║
║ ║ ║ D-114 ║ 28Z07 ║ ║
║ ║ ║ D-063 ║ 28Z17 ║ ║
║ ║ ║ D-142 ║ A-314 ║ 28Z19 ║
║ ║ ║ ║ A-315 ║ 28Z20 ║
║ ║ ║ ║ A-316 ║ 28Z21 ║
║ ║ ║ ║ A-317 ║ 28Z22 ║
║ ║ ║ ║ other ║ 90Z02Z ║
║ ║ ║ D-143 ║ A-342 ║ null ║
║ ║ ║ ║ A-205 ║ 28Z10 ║
║ ║ ║ ║ A-170 ║ 28Z11 ║
║ ║ ║ ║ A-304 ║ 28Z18 ║
║ ║ ║ ║ A-318 ║ 28Z23 ║
║ ║ ║ ║ A-319 ║ 28Z24 ║
║ ║ ║ ║ A-320 ║ 28Z25 ║
║ ║ ║ ║ other ║ 90Z02Z ║
║ ║ ║ D-139 ║ 28Z15 ║ ║
║ ║ ║ D-047 ║ 28Z15 ║ ║
║ ║ ║ D-054 ║ 28Z16 ║ ║
║ ║ ║ other ║ 90Z02Z ║ ║
║ ║ other ║ 90Z01Z ║ ║ ║
╚════════╩═══════╩════════╩════════╩════════╝
csv文件如下所示,用于cmd-28,它具有两个子D-145和另一个。对于D-145,它有那些孩子(D-113,D-114,D-063,D-142,D-143,D-139,D-047,D-054等),而另一个有一个孩子90Z01Z和对其他有孩子的孩子来说也是这样。
下面的类是我用来为每个父母分配孩子的类,它工作得很好,但是总是会弄清楚如何循环该过程。
class Node(object):
def __init__(self, key, label, leads = None):
self.key = key
self.label = label
self.leads = leads
self.children = []
self.options = []
def as_dict(self):
k = {'key': self.key}
k['label'] = self.label
if self.options:
k['options'] = [c.as_dict() for c in self.options]
if self.children:
k['children'] = [c.as_dict() for c in self.children]
if self.leads != None :
k['leadsTo'] = self.leads
return k
tree = Node("cmd-28","Cmd-28")
tree.children.append(Node("D-145","D-145"))
tree.children.append(Node("other","other"))
tree.options.append(Node("D-145","D-145","D-145"))
tree.options.append(Node("other","other","other"))
tree.children[0].children.append(Node("D-113","D-113"))
tree.children[0].children.append(Node("D-114","D-114"))
tree.children[0].options.append(Node("D-113","D-113","D-113"))
tree.children[0].options.append(Node("D-114","D-114","D-114"))
tree.children[1].children.append(Node("90Z01Z","90Z01Z"))
tree.children[1].options.append(Node("90Z01Z","90Z01Z","90Z01Z"))
print (json.dumps(tree.as_dict(), indent=4))
我需要将结果作为以下json文件:
{
"key": "cmd-28",
"label": "Cmd-28",
"options": [
{
"key": "D-145",
"label": "D-145",
"leadsTo": "D-145"
},
{
"key": "other",
"label": "other",
"leadsTo": "other"
}
],
"children": [
{
"key": "D-145",
"label": "D-145",
"options": [
{
"key": "D-113",
"label": "D-113",
"leadsTo": "D-113"
},
{
"key": "D-114",
"label": "D-114",
"leadsTo": "D-114"
}
],
"children": [
{
"key": "D-113",
"label": "D-113"
},
{
"key": "D-114",
"label": "D-114"
}
]
},
{
"key": "other",
"label": "other",
"options": [
{
"key": "90Z01Z",
"label": "90Z01Z",
"leadsTo": "90Z01Z"
}
],
"children": [
{
"key": "90Z01Z",
"label": "90Z01Z"
}
]
}
]
}
我试图将csv放入Pandas数据框中,并尝试循环并为每个父级分配自己的子级,但是失败了。