查找两个列表中都不存在的对象的最佳方法 [英] Best way to find objects not present in both lists
问题描述
我正在开发一个模块,该模块取决于检查两个列表中是否有不存在的任何对象.该实现应该在Python中进行.
I am working on a module that depends on checking if there are any objects not present in either of the 2 lists. The implementation is supposed to be in Python.
考虑简化对象def:
class Foo(object):
def __init__(self, attr_one=None, attr_two=None):
self.attr_one = attr_one
self.attr_two = attr_two
def __eq__(self, other):
return self.attr_one == other.attr_one and self.attr_two == other.attr_two
我有两个单独的列表,它们可以封装Foo类的多个实例,如下所示:
I have two separate lists that can encapsulates multiple instances of class Foo as follows:
list1 = [Foo('abc', 2), Foo('bcd', 3), Foo('cde', 4)]
list2 = [Foo('abc', 2), Foo('bcd', 4), Foo('efg', 5)]
我需要根据attr_one找出一个列表中存在的对象,而另一个列表中不存在的对象.在这种情况下,下面列出了第一个列表中存在的项目和第二个列表中缺失的项目的期望输出.
I need to figure out the objects that are present in one list and absent in the other on the basis of attr_one. In this case, the desired output for items present in first list and missing in the second list is given below.
`['Foo('bcd', 3), Foo('cde', 4)]`
类似地,项目出现在列表2中,但不在列表1中
Similarly, the items present in list 2 but not in list 1
[Foo('bcd', 4), Foo('efg', 5)]
我想知道是否还有一种方法可以匹配attr_one的基础.
I would like to know if there is a way to match the basis of attr_one as well.
List 1 List 2
Foo('bcd', 3) Foo('bcd', 4)
Foo('cde', 4) None
None Foo('efg', 5)
推荐答案
由于已经定义了__eq__
方法,因此可以使用列表推导在两个列表中的任意一个中查找对象的唯一性.
Since you already have an __eq__
method defined, You can use list comprehension to find the uniqueness of the objects in either of the lists.
print [obj for obj in list1 if obj not in list2]
这篇关于查找两个列表中都不存在的对象的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!