<p>只是一个想法。。。</p>
<pre><code>class Foo(object):
def __init__(self, id, name):
self.id = id
self.name = name
def __repr__(self):
return '({},{})'.format(self.id, self.name)
list1 = [Foo(1,'a'),Foo(1,'b'),Foo(2,'b'),Foo(3,'c'),]
list2 = [Foo(1,'a'),Foo(2,'c'),Foo(2,'b'),Foo(4,'c'),]
</code></pre>
<p>所以通常这是行不通的:</p>
<pre><code>print(set(list1)-set(list2))
# set([(1,b), (2,b), (3,c), (1,a)])
</code></pre>
<p>但是你可以教<code>Foo</code>两个实例相等意味着什么:</p>
<pre><code>def __hash__(self):
return hash((self.id, self.name))
def __eq__(self, other):
try:
return (self.id, self.name) == (other.id, other.name)
except AttributeError:
return NotImplemented
Foo.__hash__ = __hash__
Foo.__eq__ = __eq__
</code></pre>
<p>现在:</p>
<pre><code>print(set(list1)-set(list2))
# set([(3,c), (1,b)])
</code></pre>
<hr/>
<p>当然,更可能的是,您可以在类定义时在<code>__hash__</code>上定义<code>__eq__</code>和<code>Foo</code>,而无需稍后对其进行猴子修补:</p>
<pre><code>class Foo(object):
def __init__(self, id, name):
self.id = id
self.name = name
def __repr__(self):
return '({},{})'.format(self.id, self.name)
def __hash__(self):
return hash((self.id, self.name))
def __eq__(self, other):
try:
return (self.id, self.name) == (other.id, other.name)
except AttributeError:
return NotImplemented
</code></pre>
<hr/>
<p>为了满足我自己的好奇心,这里有一个基准:</p>
<pre><code>In [34]: list1 = [Foo(1,'a'),Foo(1,'b'),Foo(2,'b'),Foo(3,'c')]*10000
In [35]: list2 = [Foo(1,'a'),Foo(2,'c'),Foo(2,'b'),Foo(4,'c')]*10000
In [40]: %timeit set1 = set((x.id,x.name) for x in list1); [x for x in list2 if (x.id,x.name) not in set1 ]
100 loops, best of 3: 15.3 ms per loop
In [41]: %timeit set1 = set(list1); [x for x in list2 if x not in set1]
10 loops, best of 3: 33.2 ms per loop
</code></pre>
<p>因此@mgilson的方法更快,尽管在<code>Foo</code>中定义<code>__hash__</code>和<code>__eq__</code>会导致更可读的代码。</p>