zoukankan      html  css  js  c++  java
  • 2018.7.11 昨天晚上的列表(字典)嵌套题

    列表(字典)嵌套题

    给你一个列表:(可能还会无限的拓展下去)

    msg_list = [
        {'id': 1, 'content': 'xxx', 'parent_id': None, },
        {'id': 2, 'content': 'xxx', 'parent_id': None, },
        {'id': 3, 'content': 'xxx', 'parent_id': None, },
        {'id': 4, 'content': 'xxx', 'parent_id': 1, },
        {'id': 5, 'content': 'xxx', 'parent_id': 4, },
        {'id': 6, 'content': 'xxx', 'parent_id': 2, },
        {'id': 7, 'content': 'xxx', 'parent_id': 5, },
        {'id': 8, 'content': 'xxx', 'parent_id': 3, },
    ]
    

    要得出以下结果,你会怎么做这道题?

    [
    {'id': 1, 'content': 'xxx', 'parent_id': None, 'child': [{'id': 4, 'content': 'xxx', 'parent_id': 1, 'child': [{'id': 5, 'content': 'xxx', 'parent_id': 4, 'child': [{'id': 7, 'content': 'xxx', 'parent_id': 5, 'child': []}]}]}]}, {'id': 2, 'content': 'xxx', 'parent_id': None, 'child': [{'id': 6, 'content': 'xxx', 'parent_id': 2, 'child': []}]}, {'id': 3, 'content': 'xxx', 'parent_id': None, 'child': [{'id': 8, 'content': 'xxx', 'parent_id': 3, 'child': []}]},
    ]

    前面列表字典方面小知识的回顾

    首先是字典列表添加新项的方法回顾:

    # 字典列表添加项的方法
    
    v1 = [1,2,3,4]	# 添加列表项需要用到append函数
    v1.append(123)
    print(v1)
    
    v1 = {'k1':'v1'}	# 添加字典项和C语言的数组赋值类似
    v1['k2'] = 'v2'
    print(v1)
    

    还有一个要值得注意的就是下面这个例子:

    data = [
        [11,22,33],
        [44,55,66]
    ]
    data[0].append(data[1])
    
    ##############  结果  #################
    
    data = [
        [11,22,33, [44,55,66]],
        [44,55,66]
    ]

    如果我进行这样一个操作:

    data[1].append(77)
    

    那么data列表只会变成这样:

    data = [
        [11,22,33, [44,55,66,77]],
        [44,55,66,77]
    ]
    

    因为这其中赋值的时候传递的是地址而不是复制变量,python中大部分时候都是传递的地址,这点要特别注意!

    两种方法解决问题

    开始我认为这个问题很简单,很快我就给出了答案:

    for item_w in msg_list:
      item_w['child'] = []
        for item_l in msg_list:
            if item_w['id'] == item_l['parent_id']:
                item_w['child'].append(item_l)
    

    利用两层循环“粗暴”地解除了这个问题,之所以说这个方法很粗暴,因为这个方法当数据越来越多的时候处理效率会急速下降,想到字典的查找速度是最快的,我觉得利用字典这个特性,可以用另一种巧妙的方法解决这个问题:

    msg_2_list = {}
    for i in msg_list:
        i['child'] = []
        msg_2_list[i['id']] = i
    
    result = []
    for item in msg_list:
        if item['parent_id']:
            msg_2_list[item['parent_id']]['child'].append(item)
        else:
            result.append(item)
    

    其实就是创建了一个字典的数据结构,重新组织了一下题目的数据,方便查找到父项,只用一层循环就解决了这个问题

  • 相关阅读:
    Oracle-DQL 7- 集合操作
    Oracle-DQL 6- 子查询
    Oracle-DQL 5- 分组函数(多行函数)
    Oracle-DQL 4- 多表查询
    Oracle-DQL 3- 单行函数
    构建gulp项目
    重开Vue2.0
    ES6
    emmet简单记录
    webpack 3.X研究
  • 原文地址:https://www.cnblogs.com/yu-jie/p/9292583.html
Copyright © 2011-2022 走看看