猿问

从最后一列向动态树添加大小

我需要创建一个嵌套的 dict 结构,其中子级的数量可以在每个级别有所不同。

将“大小”元素附加到旭日形图的最后一个 json 子元素 这个问题涵盖了树的创建,除了我需要从最后一列中选取大小。

鉴于我的标签在级别之间重复,并且每个级别都可以具有与终端级别相同的标签“abc”,以及下一级的父级 - 我在这里稍微修改了代码(以避免在子分支中重复)。但是,我无法指定存储在最后一列中的大小,并且应该替换每个叶端的 1。我知道我需要将行中的值传递给递归循环 build_leaf,但似乎无法弄清楚如何。

import csv

from collections import defaultdict

import json


def ctree():

    return defaultdict(ctree)



def build_leaf(name, leaf):        

    if len(name)==0:

        res={"name":"last node"}

        res['size']=1

    else:

        res = {"name": name}


        # add children node if the leaf actually has any children

        if len(leaf.keys())>0:

            res["children"] = [build_leaf(k, v) for k, v in leaf.items()]

        else:

            res['size'] = 1


    return res


def main():

    tree = ctree()

    # NOTE: you need to have test.csv file as neighbor to this file

    with open('./inpfile.csv') as csvfile:

        reader = csv.reader(csvfile)

        header = next(reader)  # read the header row        

        i=0

        for row in reader:

            # usage of python magic to construct dynamic tree structure and

            # basically grouping csv values under their parents

            leaf = tree[row[0]]

            size=row[-1]


            for value in row[1:-1]:

                leaf = leaf[value]


    # building a custom tree structure

    res = []


    for name, leaf in tree.items():

        res.append(build_leaf(name, leaf))


    # printing results into the terminal

    print(json.dumps(res, indent=2))

    with open('paths.json', 'w') as fp:

        json.dump(res, fp)



main()

所提及数据的最终输出应类似于:


[

  {

    "name": "A1",

    "children": [

      {

        "name": "A2",

        "children": [

          {

            "name": "A1",

            "children": [

              {

                "name": "A2",

                "children": [

                  {

                    "name": "A3",

                    "size": 80

                  }

                ]

              }

            ]

          },

  

千万里不及你
浏览 173回答 1
1回答

翻过高山走不出你

万一有人偶然发现了同样的问题——我可以通过创建另一个递归循环来从嵌套的叶子中检索大小(感谢道格拉斯的帮助)来让它工作。def ctree():&nbsp; &nbsp; return defaultdict(ctree)def get_size(leaf1):&nbsp; &nbsp; for k,v in leaf1.items():&nbsp; &nbsp; &nbsp; &nbsp; if k=="size":&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return v&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return get_size(v)def build_leaf(name, leaf):&nbsp; &nbsp; if len(name)==0:&nbsp; &nbsp; &nbsp; &nbsp; res={"name":"exit site"}&nbsp; &nbsp; &nbsp; &nbsp; res['size']=int(get_size(leaf))&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; res = {"name": name}&nbsp; &nbsp; &nbsp; &nbsp; # add children node if the leaf actually has any children&nbsp; &nbsp; &nbsp; &nbsp; if not leaf["size"]:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; res["children"] = [build_leaf(k, v) for k, v in leaf.items() if not k == "size" ]&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; res['size'] = int(get_size(leaf))&nbsp; &nbsp; return resdef make_json(inpfile,outjson):&nbsp; &nbsp; tree = ctree()&nbsp; &nbsp; # NOTE: you need to have test.csv file as neighbor to this file&nbsp; &nbsp; with open("./filepath.csv") as csvfile:&nbsp; &nbsp; &nbsp; &nbsp; reader = csv.reader(csvfile)&nbsp; &nbsp; &nbsp; &nbsp; header = next(reader)&nbsp; # read the header row&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; for row in reader:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # usage of python magic to construct dynamic tree structure and&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # basically grouping csv values under their parents&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; leaf = tree[row[0]]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; size=row[-1]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for value in row[1:-1]:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; leaf = leaf[value]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if len(row) < 6:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; leaf["exit site"]["size"]=size&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; leaf["size"]=size&nbsp; &nbsp; # building a custom tree structure&nbsp; &nbsp; res = []&nbsp; &nbsp; for name, leaf in tree.items():&nbsp; &nbsp; &nbsp; &nbsp; res.append(build_leaf(name, leaf))&nbsp; &nbsp; with open(outjson, 'w') as fp:&nbsp; &nbsp; &nbsp; &nbsp; json.dump(res, fp)
随时随地看视频慕课网APP

相关分类

Python
我要回答