Python|在字典列表中设置差异
两个列表的区别已经讨论过很多次了,但是有时候我们有大量的数据,我们需要找到区别,即dict2中的元素不在1中,以减少冗余。让我们讨论一些可以做到这一点的方法。
方法#1:使用列表推导
迭代列表和提取差异的简单方法可以缩短为使用列表理解缩短代码并增加可读性的方法。
# Python3 code to demonstrate
# set difference in dictionary list
# using list comprehension
# initializing list
test_list1 = [{"HpY" : 22}, {"BirthdaY" : 2}, ]
test_list2 = [{"HpY" : 22}, {"BirthdaY" : 2}, {"Shambhavi" : 2019}]
# printing original lists
print ("The original list 1 is : " + str(test_list1))
print ("The original list 2 is : " + str(test_list2))
# using list comprehension
# set difference in dictionary list
res = [i for i in test_list1 if i not in test_list2] \
+ [j for j in test_list2 if j not in test_list1]
# printing result
print ("The set difference of list is : " + str(res))
输出 :
The original list 1 is : [{‘HpY’: 22}, {‘BirthdaY’: 2}]
The original list 2 is : [{‘HpY’: 22}, {‘BirthdaY’: 2}, {‘Shambhavi’: 2019}]
The set difference of list is : [{‘Shambhavi’: 2019}]
方法#2:使用itertools.filterfalse()
这是使用内置Python函数执行此特定任务的另一种方式。 filterfalse 方法相对于另一个列表过滤一个列表中不存在的元素。
# Python3 code to demonstrate
# set difference in dictionary list
# using itertools.filterfalse()
import itertools
# initializing list
test_list1 = [{"HpY" : 22}, {"BirthdaY" : 2}, ]
test_list2 = [{"HpY" : 22}, {"BirthdaY" : 2}, {"Shambhavi" : 2019}]
# printing original lists
print ("The original list 1 is : " + str(test_list1))
print ("The original list 2 is : " + str(test_list2))
# using itertools.filterfalse()
# set difference in dictionary list
res = list(itertools.filterfalse(lambda i: i in test_list1, test_list2)) \
+ list(itertools.filterfalse(lambda j: j in test_list2, test_list1))
# printing result
print ("The set difference of list is : " + str(res))
输出 :
The original list 1 is : [{‘HpY’: 22}, {‘BirthdaY’: 2}]
The original list 2 is : [{‘HpY’: 22}, {‘BirthdaY’: 2}, {‘Shambhavi’: 2019}]
The set difference of list is : [{‘Shambhavi’: 2019}]