分类方式、递归、树状
分类方式1:递归方式
data = [
{"cat_id": 6, "name": "昌平", "parent_id": 5},
{"cat_id": 3, "name": "青浦", "parent_id": 1},
{"cat_id": 2, "name": "张江", "parent_id": 4},
{"cat_id": 4, "name": "浦东", "parent_id": 1},
{"cat_id": 5, "name": "北京", "parent_id": 0},
{"cat_id": 1, "name": "上海", "parent_id": 0},
]
'''
上海
-浦东
--张江
-青浦
北京
-昌平
'''
res = []
def sone(data, level=0, parent_id=0):
for item in data:
if item['parent_id'] == parent_id:
item['level'] = level
res.append(item)
sone(data, level + 1, item['cat_id'])
return res
t = sone(data)
print(t)
for i in t:
print(i['level'] * '-',i['name'])
'''
t= [{'cat_id': 5, 'name': '北京', 'parent_id': 0, 'level': 0},
{'cat_id': 6, 'name': '昌平', 'parent_id': 5, 'level': 1},
{'cat_id': 1, 'name': '上海', 'parent_id': 0, 'level': 0},
{'cat_id': 3, 'name': '青浦', 'parent_id': 1, 'level': 1},
{'cat_id': 4, 'name': '浦东', 'parent_id': 1, 'level': 1},
{'cat_id': 2, 'name': '张江', 'parent_id': 4, 'level': 2}]
'''
分类方式2:树状
data = [
{"cat_id": 3, "name": "青浦", "parent_id": 1},
{"cat_id": 2, "name": "张江", "parent_id": 4},
{"cat_id": 4, "name": "浦东", "parent_id": 1},
{"cat_id": 5, "name": "北京", "parent_id": 0},
{"cat_id": 6, "name": "昌平", "parent_id": 5},
{"cat_id": 1, "name": "上海", "parent_id": 0},
]
'''
tree={
3:{"cat_id":3,"name":"青浦","parent_id":1},
2:{"cat_id": 2, "name": "张江", "parent_id": 4},
4:{"cat_id":4,"name":"浦东","parent_id":1},
5:{"cat_id":5, "name": "北京", "parent_id": 0},
6:{"cat_id":6, "name": "昌平", "parent_id": 5},
1:{"cat_id": 1, "name": "上海", "parent_id": 0},
}
'''
def get_tree(data):
lists = []
tree = {}
for i in data:
tree[i['cat_id']] = i
for item in data:
if item['parent_id'] == 0:
dict1 = tree[item['cat_id']]
lists.append(dict1)
else:
dict2 = tree[item["parent_id"]]
if "children" not in dict2:
dict2['children'] = []
dict2['children'].append(tree[item['cat_id']])
return lists
print(get_tree(data))
'''
get_tree(data) = [
{'cat_id': 5, 'name': '北京', 'parent_id': 0,
'children': [
{'cat_id': 6, 'name': '昌平', 'parent_id': 5}
]
},
{'cat_id': 1, 'name': '上海', 'parent_id': 0,
'children': [
{'cat_id': 3, 'name': '青浦', 'parent_id': 1},
{'cat_id': 4, 'name': '浦东', 'parent_id': 1,
'children': [
{'cat_id': 2, 'name': '张江', 'parent_id': 4}
]
}
]
}
]
'''
这样就可以通过循环嵌套的级数显示几级分类。
for item in data1:
print("一级分类:",item['name'])
for item1 in item["children"]:
print("二级分类:",item1.get('name'))
选择了IT,必定终身学习