python实现list动态嵌套

python实现list动态嵌套,第1张

python实现list动态嵌套

实现效果如下:

[

{"city": "上海",

"cityID": "shanghai",

"districts": [{"distrID": 1, "district": "浦东新区", "image": "/img/shanghai/pudong.jpg"},

                {"distrID": 2, "district": "徐汇区", "image": "/img/shanghai/xuhui.jpg"},

                {"distrID": 3, "district": "黄浦区", "image": "/img/shanghai/huangpu.jpg"}]                

},

{"city": "北京",

"cityID": "beijing",

"districts": [{"distrID": 4, "district": "朝阳区", "image": "/img/beijing/chaoyang.jpg"},

                {"distrID": 5, "district": "海淀区", "image": "/img/beijing/haidian.jpg"},

                {"distrID": 6, "district": "昌平区", "image": "/img/beijing/changping.jpg"}]                

}

]

​
def cityList(request):
    cityDistinct = distrs.objects.values("city").distinct() //在distrs表中获取不同的城市
    cities=[]   //城市list
    for i in cityDistinct: //对每个城市进行遍历
        distrDistinct = distrs.objects.filter(district=i['city']) //从distrs表中获取该城市包含的区
        districts = [] //区域list
        for j in distrDistinct: //对每个区进行遍历,插入区域相关信息
            districts.append({'distrID': j.distrID, 'district': j.district, 
                            'image': j.image}) 
        //对该城市的所有区遍历结束,将districts插入城市list中
        cities.append({'city': i['city'], 'cityID': i['cityID'], 'districts': districts}) 
    cities_json = json.dumps(cities, ensure_ascii=False)
    return HttpResponse(cities_json)

​

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5700888.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存