美文网首页
树形结构数据改变

树形结构数据改变

作者: 领带衬有黄金 | 来源:发表于2019-12-18 17:35 被阅读0次
image.png

待优化

from functools import reduce

data = {
    "a_b_h": 1,
    "a_b_i": 2,
    "a_c_j": 3,
    "a_d": 4,
    "a_c_k": 5,
    "a_e": 6
}
ret = []
for i in data:
    tmp = i.split('_')
    tmp.append(data[i])
    ret.append(tmp)
print(ret)


def f(d):
    if len(d) == 1:
        return d[0]
    if len(d) > 1:
        return {d[0]: f(d[1:])}


def dicMeg(dic1, dic2):
    """嵌套字典合并"""
    for i in dic2:
        if i in dic1:
            if type(dic1[i]) is dict and type(dic2[i]) is dict:
                dicMeg(dic1[i], dic2[i])
        else:
            dic1[i] = dic2[i]


new_data = []
for i in ret:
    tmp = f(i)
    new_data.append(tmp)
print(new_data)
# print(reduce(dicMeg, new_data))
ccc = {}
for i, j in enumerate(new_data):
    if i == len(new_data) - 1:
        break
    dicMeg(new_data[0], new_data[i + 1])
print(new_data[0])

优化后:

from functools import reduce

data = {
    "a_b_h": 1,
    "a_b_i": 2,
    "a_c_j": 3,
    "a_d": 4,
    "a_c_k": 5,
    "a_e": 6
}


def h(d):
    """
    将数据格式化输出:如下
    :param d:[['a', 'b', 'h', 1], ['a', 'b', 'i', 2], ['a', 'c', 'j', 3], ['a', 'd', 4], ['a', 'c', 'k', 5], ['a', 'e', 6]]
    :return:
    """
    return [i.split('_') + [d[i]] for i in d]


def f(d):
    """将每一条数据转化为字典
    输出:['a', 'b', 'h', 1]: 1-->{a:{b:{h:1}}}
    """
    if len(d) == 1:
        return d[0]
    if len(d) > 1:
        return {d[0]: f(d[1:])}


def dict_merge(dic1, dic2):
    """嵌套字典合并"""
    for i in dic2:
        if i in dic1:
            if type(dic1[i]) is dict and type(dic2[i]) is dict:
                dict_merge(dic1[i], dic2[i])
        else:
            dic1[i] = dic2[i]
    return dic1


if __name__ == '__main__':
    ret = h(data)
    new_data = [f(i) for i in ret]
    print(reduce(dict_merge, new_data))

相关文章

网友评论

      本文标题:树形结构数据改变

      本文链接:https://www.haomeiwen.com/subject/cabunctx.html