我的目標是獲得包含對象的兩個列表之間的差異。在Python中使用散列獲取兩個對象列表之間的差異
我已經實現了一個名爲科類和如下覆蓋其__eq__
和__ne__
方法:
class Branch(object):
def __str__(self):
return self.name
def __eq__(self, other):
if isinstance(other, Branch):
return (self.valueFrom == other.valueFrom) \
and (self.valueTo == other.valueTo) \
and (self.inService == other.inService)
return NotImplemented
def __ne__(self, other):
result = self.__eq__(other)
if result is NotImplemented:
return result
return not result
def __init__(self, name, valueFrom, valueTo, inService=True):
self.name = name
self.valueFrom = valueFrom
self.valueTo = valueTo
self.inService = inService
我第一次嘗試是從set
型使用的方法difference
。然而,看起來這是不可能的,因爲它使用了對象的散列,而不是我想要的那樣使用__eq__
方法。
下面的代碼顯示問題:
b1 = Branch("branch1", 1, 2)
b1b = Branch("equal to branch1", 1, 2)
b2 = Branch("branch2", 2, 3)
b3 = Branch("branch3", 3, 1)
b3_off = Branch("branch3 not in service", 3, 1, False)
l1 =[b1,b2,b3]
l2 =[b1b,b2,b3_off]
difference = set(l1).difference(l2)
for branch in difference:
print branch
輸出是:
>>>
branch1
branch3
不過,我希望得到的輸出僅作爲店3和b1
應該b1b
平等對待。
是否可以使用sets來解決這個問題?或者我應該從不同的角度來看問題嗎?
可能重複[獲取兩個列表之間的差異](http://stackoverflow.com/questions/3462143/get-difference-between-two-lists) –