python - Python中使用哈希获取两个对象列表之间的差异

标签 python list object set difference

我的目标是获取两个包含对象的列表之间的差异。

我已经实现了一个名为 Branch 的类并覆盖了它的 __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

我的第一次尝试是使用方法 difference来自set类型。然而,这似乎是不可能的,因为它使用对象的哈希值而不是 __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

但是我希望仅将branch3作为输出b1b1b应该平等对待。

是否可以使用集合来解决这个问题?或者我应该从不同的角度来处理这个问题?

最佳答案

您需要实现哈希,您选择什么取决于您,但以下内容可以工作:

def __hash__(self):
    return hash((self.valueFrom , self.valueTo , self.inService))

您需要实现的只是 hash 和 eq:

class Branch(object):
    def __init__(self, name, valueFrom, valueTo, inService=True):
        self.name = name
        self.valueFrom = valueFrom
        self.valueTo = valueTo
        self.inService = inService

    def __eq__(self, other):
        if isinstance(other, Branch):
            return (self.valueFrom,self.valueTo,self.inService )\
                   ==(other.valueFrom, other.valueTo, other.inService)
        return NotImplemented

    def __str__(self):
        return self.name

    def __hash__(self):
        return hash((self.valueFrom, self.valueTo,self.inService))

关于python - Python中使用哈希获取两个对象列表之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39923021/

相关文章:

python - 将列表元素作为函数的参数一一传递

python - 从远程 Linux 服务器连接到 mongoDb 时如何修复 Python 中的 "[Errno 111] Connection refused"错误

python - 如何对正则表达式中的某些单词进行异常(exception)处理

python - 替换主词典中的用户输入列表元素?

java - 我如何在java中读取多行文本,行与行之间有空格

java - Java 中的 ArrayList 的 ArrayList - 缩短代码

java - 我可以访问最终对象的方法吗?

python - Pandas 相关矩阵与 value_counts 列字符串

JavaScript 对象对于所有版本的 Google Chrome 都是唯一的?

java 。为什么它对英语和斯拉夫字符的处理方式不同?