# 1. 有两个列表,其中一个列表a,每一项映射到另一个列表b每一项,先对a排序,要求b的中映射关系位置保持不变,给b也按照排序, (b的8对应a的[1,2], 7对应[3,4] ... )
a = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]
b = [8, 7, 9, 7, 9]
def relation(a,b):
relation = {}
for index, item in enumerate(a):
relation[tuple(item)] = b[index]
new_a = [list(i) for i in sorted(relation, key=lambda x: relation[x])]
new_b = sorted(b)
return new_a, new_b
a,b = relation(a,b)
print(a)
print(b)
"""
2. 将一维列表根据父节点,折叠起来
menu_list = [
{'id':1,'title':'菜单1','pid':None},
{'id':2,'title':'菜单2','pid':None},
{'id':3,'title':'菜单3','pid':None},
{'id':4,'title':'菜单1.1','pid':1},
{'id':5,'title':'菜单1.2','pid':1},
{'id':6,'title':'菜单2.1','pid':2},
{'id':7,'title':'菜单3.1','pid':3},
{'id':8,'title':'菜单1.1.1','pid':4},
{'id':9,'title':'菜单1.2.1','pid':5},
{'id':10,'title':'菜单4','pid':None},
]
结果:
result = [
{'id':1,'title':'菜单1','pid':None,children:[
{'id':4,'title':'菜单1.1','pid':1,children:[
{'id':8,'title':'菜单1.1.1','pid':4,children:[]},
]},
{'id':5,'title':'菜单1.2','pid':1,children:[
{'id':9,'title':'菜单1.2.1','pid':5},
]},
]},
{'id':2,'title':'菜单2','pid':None..},
{'id':3,'title':'菜单3','pid':None..},
{'id':10,'title':'菜单4','pid':None..},
]
"""
# 方法一
new_dic = {}
for i in menu_list:
new_dic[i['id']] = i
for v in new_dic.values():
pid = v['pid']
if pid:
new_dic[pid].setdefault('childern', [])
new_dic[pid]['childern'].append(v)
result = [i for i in menu_list if not i['pid']]
# 方法二
temp_list = menu_list.copy()
for i in menu_list:
i['children'] = []
pid = i['pid']
if i['pid']:
temp_list[pid-1]['children'].append(i)
result = [i for i in temp_list if not i['pid']]