首页 > 解决方案 > 如何从集合中删除对象而不考虑顺序

问题描述

我无法从集合中移除对象。我所做的是,创建一个测试类并在其中存储两个变量。它是一个字符串变量。我需要将我创建的对象存储到一个集合中,以及任何(ta,tb)与(tb,ta)相同的对象。因此,每当我将元组添加到我的集合中时,我都无法删除相反的条件。有没有办法在python中做到这一点?

class Test:
    def __init__(self, a, b):
        self.a = a
        self.b = b
        self.variables = [a, b]

    def __hash__(self):
        return hash((self.a, self.b))

    def __eq__(self, other: Test):
        return type(self) is type(other) and self.endpoint() == other.endpoint() or 
        self.endpoint() == other.endpoint()[::-1]

    def endpoint(self):
        return (self.a, self.b)

T = Test('A','B')
T2 = Test("B",'A")
result = set()
result.add(T)
result.add(T2)

However, result is showing me both the objects in it as opposed to one.  Is there a way to fix this?  Thanks

标签: python-3.xset

解决方案


推荐阅读