Python检查值是否在lis中的对象内部

2024-04-23 13:46:02 发布

您现在位置:Python中文网/ 问答频道 /正文

像这样的事情

class Obj:
    def __init__(self, x, y):
        self.x = x
        self.y = y


li = [Obj(0, 0), Obj(0, 1), Obj(2, 3)]

print(Obj(2,3) in li)

我有一个错误的输出,因为即使x和y是相同的,它也将对象计算为不同的实例。我可以在列表中使用循环并检查

if(2==o.x and 3==o.y):
    return True

有没有更干净的方法不用循环就能得到这个?你知道吗


Tags: and对象实例inselfobj列表if
2条回答

==!=的特殊方法:

class Obj:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __eq__(self, Object):
        """ == comparison method."""
        return self.x == Object.x and self.y == Object.y

    def __ne__(self, Object):
        """ != comparison method."""
        return not self.__eq__(self, Object)

在类中实现如下函数__eq__。你知道吗

def __eq__(self,  x,y):
     if self.x==x and self.y==y:
        return True

然后使用列表理解遍历对象的list。你知道吗

result = any(Obj(2,3) == i for i in obj_list )

相关问题 更多 >