Python中對具有邏輯結構的字典進行展開爲列表

利用字典存儲樹圖,如何展開爲列表呢?

來源:我的一個小代碼稱鹽程序設計https://github.com/wan230114/chenyan-python/blob/master/V3/expand_dict.py

# -*- coding: utf-8 -*-
# @Author: ChenJun
# @Qmail:  [email protected]
# @Date:   2019-12-24 11:05:08
# @Last Modified by:   JUN
# @Last Modified time: 2019-12-24 21:38:24

"""
遍歷輸出嵌套字典

假如存在字典:
D = {
    1: {21: {28: {},
             29: {},
             30: {300: {301: {302: {}}}},
             32: {300: {}}},
        22: {33: {}}}, }

字典關係:
1   21  28
        29
        30  300 301 302
        32  300
    22  33

需要輸出以下結果,如何實現呢?
結果:
1   21  28
1   21  29
1   21  30  300 301 302
1   21  32  300
1   22  33
"""

from pprint import pprint


def expand_values(D):
    L = []
    i = -1
    for key in D.copy():
        i += 1
        D_key_len = len(D[key])
        if i == 0:
            # print('key:', key, "len:", D_key_len)
            if not D[key]:
                L.append([key, D_key_len + 1])
                D.pop(key)
                # print('-'*50)
            else:
                L.append([key, D_key_len])
                L += expand_values(D[key])
    return L


def expand_dict(D):
    L_result = []
    # 開頭處理
    # print('遍歷開始:')
    L = Ltmp = expand_values(D)
    # print(L)
    L_clean = [x[0] for x in L]
    L_result.append(L_clean)
    # 循環處理
    while D:
        L = expand_values(D)  # 遞歸生成多個行的序列
        if L != Ltmp[:len(L)]:
            # print(L)
            L_clean = [x[0] for x in L]
            L_result.append(L_clean)
        Ltmp = L

    # print('展開結果爲:')
    # pprint(L_result)
    return L_result


if __name__ == '__main__':
    D = {
        (1, 1): {
            (21, 2): {(28, 3): {},
                      (29, 3): {},
                      (30, 3): {(300, 4): {(301, 5): {(302, 6): {}}}},
                      (32, 3): {(300, 4): {}}},
            (22, 2): {(33, 3): {}}}, }
    L = expand_dict(D)
    pprint(L)

運行結果:

[[(1, 1), (21, 2), (28, 3)],
 [(1, 1), (21, 2), (29, 3)],
 [(1, 1), (21, 2), (30, 3), (300, 4), (301, 5), (302, 6)],
 [(1, 1), (21, 2), (32, 3), (300, 4)],
 [(1, 1), (22, 2), (33, 3)]]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章