[英]Python - Compare two lists of dict and return dicts from one list
I have two lists, a = [dict1, dict2, dict3]
and b = [dict1, dict2, dict4, dict5, dict6]
我有两个列表,
a = [dict1, dict2, dict3]
和b = [dict1, dict2, dict4, dict5, dict6]
I want to create two more lists, with the dicts from both lists not found in the other. 我想再创建两个列表,两个列表中的字典在另一个列表中找不到。 So they would be,
所以他们会的
c = [dict3] and d = [dict4, dict5]
I have tried the following but it returns way to many dicts 我已经尝试了以下方法,但是它可以返回许多命令
for i, j in [(i,j) for i in range(len(a)) for j in range(len(b))]:
if cmp(b[j],a[i]) == 1 or -1:
new_prods = {}
new_prods = a[i]
c.append(new_prods)
for i, j in [(i,j) for i in range(len(a)) for j in range(len(b))]:
if cmp(b[j],a[i]) == 0:
old_prods = {}
old_prods = b[j]
d.append(old_prods)
Thanks in advance 提前致谢
A simple O(n^2) solution: 一个简单的O(n ^ 2)解决方案:
a = [dict1, dict2, dict3]
b = [dict1, dict2, dict4, dict5, dict6]
c = dicts_from_a_not_in_b = [x for x in a if x not in b]
d = dicts_from_b_not_in_a = [x for x in b if x not in a]
In my opinion using sets would make perfect sense in this case. 在我看来,在这种情况下使用集合是很有意义的。
c = set(a).difference(b)
d = set(b).difference(a)
You can convert the sets to list by simply wrapping them by list(c) & list(d) 您可以通过简单地将它们包装成list(c)和list(d)将其转换为列表
Here is an alternate way to do it reusing a function: 这是重用函数的另一种方法:
a = [dict1, dict2, dict3]
b = [dict1, dict2, dict4, dict5, dict6]
def find_uncommon_elements(list1, list2):
list3 = []
for item in list1:
if item not in list2:
list3.append(item)
return list3
c = find_uncommon_elements(a,b)
d = find_uncommon_elements(b,a)
Writing a function helps in the event that you have to reuse this again later with a different set of dictionary lists, without having rewrite the entire function. 编写函数有助于在以后不得不重新使用另一组字典列表的情况下重新使用此函数,而不必重写整个函数。
This will return: 这将返回:
c = [dict3]
d = [dict4, dict5, dict6]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.