python复杂数据转换格式笔记

 list.append(dict) dict同名会被覆盖,只用用直接append键值对的方式实现

a = [(1, '192.xxx.1.xx', 1, '018xx1'), (2, '192.xxx.1.xx', 1, 'Door1'), (2, '192.xxx.1.xx', 2, 'Door2'),
     (3, '192.xxx.1.xx', 1, '011xx1'), (3, '192.xxx.1.xx', 2, '013402'), (3, '192.xxx.1.xx', 3, '013403'),
     (3, '192.xxx.1.xx', 4, '013xx4')]

list_id = []
xiabiao = {}
x = 0
target = {}
target_list = []

# 获取相同id的下标生成列表
for i in a:
    if i[0] not in list_id:
        list_id.append(i[0])
        xiabiao[i[0]] = str(x)
    else:
        xiabiao[i[0]] += ',' + str(x)
    x += 1
# print(xiabiao)  # {1: '0', 2: '1,2', 3: '3,4,5,6'}

# 这样循环xiabiao这个字典的时候
# 每一次外部循环就能得到下标字符 第一次 '0' 第二次 '1,2' 第三次 '3,4,5,6'
for q, y in xiabiao.items():
    # 将下标字符串转换为列表遍历
    z = y.split(',')
    # print(z)  # ['0']  ['1,2']  ['3,4,5,6']
    children_list = []
    children = {}
    # 这里还是外部循环 所以他们的id 和 name 是相同的只需要赋值一次 后面直接在target_list中去添加了 所以这两行可以省略
    # target["id"] = a[int(z[0])][0]
    # target["name"] = a[int(z[0])][1]

    # 内部循环得到多个 value和door
    for i in z:
        children_list.append({"value": a[int(i)][2], "door": a[int(i)][3]})
        target["children"] = children_list
    # print(children_list)  # 'children': [{'value': 1, 'door': 'Door1'}, {'value': 2, 'door': 'Door2'}]
    target_list.append({"id": a[int(z[0])][0], "name": a[int(z[0])][1], "children": children_list})
# print(target_list)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值