亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從最后一列向動態樹添加大小

從最后一列向動態樹添加大小

千萬里不及你 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 關注
  • 154 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號