list1 = [{'name': 'Tom', 'score':90}, {'name': 'Jack', 'score':86}, {'name': 'Lisa', 'score':81}, {'name': 'Bill', 'score':70}]
list2 = [{'name': 'Jack', 'score':86}, {'name': 'Bill', 'score':70}, {'name': 'Bob', 'score':48}]
怎么把 list1 和 list2 去重合并到一个新的 list_all (保持 score 的顺序),把重合的部分拆分到一个新的 list_new:
list_all = [{'name': 'Tom', 'score':90}, {'name': 'Jack', 'score':86}, {'name': 'Lisa', 'score':81}, {'name': 'Bill', 'score':70}, {'name': 'Bob', 'score':48}]
list_new = [{'name': 'Jack', 'score':86}, {'name': 'Bill', 'score':70}]
4 回答
拉丁的传说
TA贡献1789条经验 获得超8个赞
# 获取list_all
list_all = list1 + [item for item in list2 if item not in list1]
# 显式给list_all排序
list_all.sort(cmp=lambda x,y: cmp(x['score'], y['score']), reverse=True)
# 获取list_new
list_new = [item for item in list2 if item in list1]
# 显式给list_new排序
list_new.sort(cmp=lambda x,y: cmp(x['score'], y['score']), reverse=True)
开心每一天1111
TA贡献1836条经验 获得超13个赞
set1 = set([frozenset(i.items()) for i in list1])
set2 = set([frozenset(i.items()) for i in list2])
list_all = sorted(set1|set2,key = lambda k:dict(k)['score'],reverse = True)
list_new = sorted(set1&set2,key = lambda k:dict(k)['score'],reverse = True)
添加回答
举报
0/150
提交
取消