怎么把 list1 和 list2 中包含的重复字典去除,合并生成一个新的 list_all?

2016-12-16 11:42:27 +08:00
 rogwan

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}]

4084 次点击
所在节点    Python
26 条回复
practicer
2016-12-17 10:00:03 +08:00
from operator import itemgetter
from collections import Counter

# 合并列表, 思路是先将字典转为可哈希的元组
list_merged = [dict(t) for t in set([tuple(d.items()) for d in list1+list2])]

# 根据字典某个值来排序, 官方库有推荐姿势 -- operator.itemgetter
sorted(list_merged, key=lambda k: k['score'], reverse=True) # 没用 itemgetter
sorted(list_merged, key=itemgetter('score'), reverse=True) # 使用 itemgetter

# 保存重合项
list_tuple = [tuple(d.items()) for d in list1+list2] # 仍先转为元组, 使其可哈希
counts = Counter(list_tuple) # 通过 collections.Counter 查找重复项, 只接受可哈希对象
item_dups = set([i for i in list_tuple if counts[i] > 1]) # 保留出现次数大于 1 的项, 并去重
list_new = [dict(t) for t in item_dups] # 元组转回到字典对象
jayli
2016-12-17 14:13:55 +08:00
@leeyiw 用集合的合并
mark06
2016-12-19 17:18:32 +08:00
import numpy as np
list_unique=list(np.unique(np.array(list1+list2)))
mark06
2016-12-19 17:37:31 +08:00
@mark06 补上交集的
list_inter = list(np.intersect1d(list1, list2))
182247236
2016-12-21 00:30:13 +08:00
@cxyfreedom 试了下你的方法..无法去除重复,明天我也试下
182247236
2016-12-21 09:50:45 +08:00
list_new = []
list_all = []
list_only = []
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}]

# list_new = [i for i in list1 if i in list2]
for i in list1:
if i in list2:
list_new.append(i)
else:
list_only.append(i)

list_all = list_only+list_new

print(list_new)
print(list_all)

虽然实现了 lisr_new 和 list_all ,但是发现 lsit_all 没保持 score 的顺序,试着 list_all = sorted(list_only+list_new),结果 typeerror 。 T,T

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/328043

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX