列表python中的对象比较,带有索引值

梅里克·奥兹坎(Meric Ozcan)

可以说我有一堂课

class Foo:
    def __init__(self, item1, item2):
        self.item1 = item1
        self.item2 = item2

以及该类的对象列表

object1 = Foo (1,2)  
object2 = Foo (1,2)
object3 = Foo (1,3)
objectlist = [object1, object3]

我想知道具有相同项目的object2是否在objectlist列表中,之后我想获取它的索引。在这种情况下,索引为0。

我可以这样

def __eq__ (self, other):
    return (self.item1 == other.item1) and (self.item2 == other.item2)

和一个for循环。因为我可以逐个检查每个索引,并获得等于该对象的索引。但是我可以用更卑鄙的方式做到吗?

洛克·格里斯

怎么样?:

class Foo:
    def __init__(self, item1, item2):
        self.item1 = item1
        self.item2 = item2


    def __eq__ (self, other):
        return (self.item1 == other.item1) and (self.item2 == other.item2)

object1 = Foo (1,2)  
object2 = Foo (1,2)
object3 = Foo (1,3)
objectlist = [object1, object3]

try:
    index_value = objectlist.index(object2)
    print(index_value)
except ValueError:
    index_value = -1
    print(index_value)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章