为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

千万里不及你 2022-06-22 15:31:32
我需要创建一个嵌套的 dict 结构,其中子级的数量可以在每个级别有所不同。将“大小”元素附加到旭日形图的最后一个 json 子元素 这个问题涵盖了树的创建,除了我需要从最后一列中选取大小。鉴于我的标签在级别之间重复,并且每个级别都可以具有与终端级别相同的标签“abc”,以及下一级的父级 - 我在这里稍微修改了代码(以避免在子分支中重复)。但是,我无法指定存储在最后一列中的大小,并且应该替换每个叶端的 1。我知道我需要将行中的值传递给递归循环 build_leaf,但似乎无法弄清楚如何。import csvfrom collections import defaultdictimport jsondef 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 resdef 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                  }                ]              }            ]          },  
查看完整描述

1 回答

?
翻过高山走不出你

TA贡献1875条经验 获得超3个赞

万一有人偶然发现了同样的问题——我可以通过创建另一个递归循环来从嵌套的叶子中检索大小(感谢道格拉斯的帮助)来让它工作。


def ctree():

    return defaultdict(ctree)


def get_size(leaf1):

    for k,v in leaf1.items():

        if k=="size":

            return v

        else:

            return get_size(v)



def build_leaf(name, leaf):


    if len(name)==0:

        res={"name":"exit site"}

        res['size']=int(get_size(leaf))


    else:

        res = {"name": name}


        # add children node if the leaf actually has any children

        if not leaf["size"]:

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

        else:

            res['size'] = int(get_size(leaf))


    return res


def make_json(inpfile,outjson):

    tree = ctree()

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

    with open("./filepath.csv") as csvfile:

        reader = csv.reader(csvfile)

        header = next(reader)  # read the header row        


        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]

            if len(row) < 6:

                leaf["exit site"]["size"]=size

            else:

                leaf["size"]=size


    # building a custom tree structure

    res = []


    for name, leaf in tree.items():

        res.append(build_leaf(name, leaf))


    with open(outjson, 'w') as fp:

        json.dump(res, fp)


查看完整回答
反对 回复 2022-06-22
  • 1 回答
  • 0 关注
  • 172 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号